Making string-formatting smarter by handling generators?

Tim Chase python.list at tim.thechases.com
Wed Feb 27 15:41:32 EST 2008


>> Is there an easy way to make string-formatting smart enough to
>> gracefully handle iterators/generators?  E.g.
>>
>>    transform = lambda s: s.upper()
>>    pair = ('hello', 'world')
>>    print "%s, %s" % pair # works
>>    print "%s, %s" % map(transform, pair) # fails
>>
>> with a """
>> TypeError:  not enough arguments for format string
>> """
> 
> Note that your problem has nothing to do with map itself. String  
> interpolation using % requires either many individual arguments, or a  
> single *tuple* argument. A list is printed as itself.
> 
> py> "%s, %s" % ['hello', 'world']
> Traceback (most recent call last):
>    File "<stdin>", line 1, in <module>

I hadn't ever encountered this, as I've always used tuples 
because that's what all the example code used.  I thought it had 
to do with indexability/iteration, rather than tuple'ness. 
Apparently, my false assumption.  People apparently use tuples 
because that's the requirement, not just because it reads well or 
is better/faster/smarter than list notation.

:)

> TypeError: not enough arguments for format string
> py> "%s" % ['hello', 'world']
> "['hello', 'world']"
> 
> So the answer is always use tuple(...) as others pointed.

I'll adjust my thinking on the matter, and mentally deprecate 
map() as well.

Thanks to all who responded.

-tkc






More information about the Python-list mailing list