converting a sed / grep / awk / . . . bash pipe line into python

Roy Smith roy at panix.com
Wed Sep 3 07:54:46 EDT 2008


In article <g9ldi5$2ea$03$1 at news.t-online.com>,
 Peter Otten <__peter__ at web.de> wrote:

> Without them it looks better:
> 
> import sys
> for line in sys.stdin:
>     try:
>         a, b = map(int, line.split(None, 2)[:2])
>     except ValueError:
>         pass
>     else:
>         if a + b == 42:
>             print b

I'm philosophically opposed to one-liners like:

>         a, b = map(int, line.split(None, 2)[:2])

because they're difficult to understand at a glance.  You need to visually 
parse it and work your way out from the inside to figure out what's going 
on.  Better to keep it longer and simpler.

Now that I've got my head around it, I realized there's no reason to make 
the split part so complicated.  No reason to limit how many splits get done 
if you're explicitly going to slice the first two.  And since you don't 
need to supply the second argument, the first one can be defaulted as well.  
So, you immediately get down to:

>         a, b = map(int, line.split()[:2])

which isn't too bad.  I might take it one step further, however, and do:

>         fields = line.split()[:2]
>         a, b = map(int, fields)

in fact, I might even get rid of the very generic, but conceptually 
overkill, use of map() and just write:

>         a, b = line.split()[:2]
>         a = int(a)
>         b = int(b)



More information about the Python-list mailing list