One-liners in Python? Not a chance!
When I recently told someone that I often use awk when I write shell scripts, the comment, together with a raised eyebrow, was "So, anyone's still using this?!" I felt a bit old-fashioned, and when today I caught myself writing a one-liner in awk I decided to give Python a chance (yes, I know, there is also Perl, but I never give Perl another chance :-/).
The problem I wanted to solve was splitting a comma-separated list into a whitespace separated list of words that I could use for iteration in the shell. The awk one-liner I came up with after 1 minute was this:
echo a,b,c | awk '{split($0,parts,",");for (i in parts) {print parts[i]}}'
I imagined the corresponding Python program would look something like this:
import sys for part in sys.stdin.read().split(","): print part
I spent maybe half an hour trying to figure out how to convert this into a one-liner, then I gave up. Incredible but true: The issue here is Python's indentation-defines-scope syntax. This syntax makes it virtually impossible to write any kind of control structure (i.e. something that uses if
, for
or while
) in a single line.
The bad (or sad) thing about this is that it makes Python a lot less useful for quick-and-dirty shell scripting. The good thing is... awk lives on, and I feel a lot less old-fashioned :-)
Comments
Karbon
2013-04-26T10:27:33+02:00
one liner
from sys import stdin; print('\n'.join(a for a in stdin.read().split(','))
patrick
2013-05-17T21:00:57+02:00
hah!
Thanks for that! Not that I am too happy about the syntax, but that's probably me, I am just not used to Python. Two remarks (in case someone else is reading this):