String concatenation
Dave Benjamin
ramen at lackingtalent.com
Mon Apr 5 03:10:51 EDT 2004
In article <7xr7v5fm3o.fsf at ruckus.brouhaha.com>, Paul Rubin wrote:
> "Leif B. Kristensen" <junkmail at solumslekt.org> writes:
>> > tmp = [x for x in res if x and x[0] != '-']
>> > return ', '.join(tmp)
>>
>> Substituting tmp with the real thing, it turns into a one-liner:
>>
>> return ', '.join([x for x in res if x and x[0] != '-'])
>>
>> Awesome :-)
>
> Yeah, I wrote it that way at first, but figured it was obscure enough
> already if you weren't used to list comprehensions, so I put back the
> tmp variable.
FWIW, I'm used to seeing (and writing) stuff like this, and I don't think
the "tmp" adds any clarity. You could wrap around it with a function,
though, if you needed it often enough:
def join_if(pred, seq, sep):
return sep.join([x for x in seq if pred(x)])
def valid(x):
return x and x[0] != '-'
return join_if(valid, res, ', ')
--
.:[ dave benjamin: ramen/[sp00] -:- spoomusic.com -:- ramenfest.com ]:.
: please talk to your son or daughter about parametric polymorphism. :
More information about the Python-list
mailing list