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

Peter Otten __peter__ at
Wed Sep 3 14:19:19 CEST 2008

Roy Smith wrote:

> In article <g9ldi5$2ea$03$1 at>,
>  Peter Otten <__peter__ at> 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 

I'm not, as long as you don't /force/ the code into one line.

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

I agree that the above is an improvement.
> 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)

If you go that route your next step is to introduce another try...except,
one for the unpacking and another for the integer conversion...


More information about the Python-list mailing list