One-liners in Python? Not a chance!

Posted on: Thu, 29 Oct 2009 10:27 By: patrick

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","):
    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 :-)


Member for

48 years 11 months

from sys import stdin; print('\n'.join(a for a in','))

Flattr name

Member for

12 years 9 months

In reply to by Karbon (not verified)

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):

  1. There should be an additional closing parenthesis, otherwise Python barfs and says "SyntaxError: unexpected EOF while parsing"
  2. The following one-liner prints 4 lines instead of the expected 3, the last line is an empty line.
echo a,b,c | python -c "from sys import stdin; print('\n'.join(a for a in',')))"

Add new comment

The content of this field is kept private and will not be shown publicly.

Filtered HTML

  • Allowed HTML tags: <h1> <pre> <br> <a href hreflang> <em> <strong> <cite> <blockquote cite> <code> <ul type> <ol start type='1 A I'> <li> <dl> <dt> <dd> <h2 id='jump-*'> <h3 id> <h4 id> <h5 id> <h6 id>
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.
CAPTCHA This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.