positional modifiers in python?

Huaiyu Zhu huaiyu at gauss.almadan.ibm.com
Fri Jun 7 18:24:13 EDT 2002


Eric Brunel <eric.brunel at pragmadev.com> wrote:
>fuf wrote:
>>  hello everyone,
>> 
>>  does python support positional parameters in the print method? ie.
>>  something like:
>>     print "there %2$s something %1$s" % ("there", "is")
>>  it doesn't work but maybe there's some other way?
>
>There's an utterly ugly way to do this:
>
>def toPosDict(l):
>  d = {}
>  map(lambda k,v,d=d: d.update({str(k):v}), range(len(l)), l)
>  return d
>print "there %(1)s something %(0)s" % toPosDict(("there", "is"))
>
>For post-Python 2.2 users (I'm still 2.1, sorry), the "map" line may 
>certainly be replaced by:
>
>map(d.__setitem__, [str(i) for i in range(len(l))], l)
>
>but it may be less efficient than the code above (one map + one list 
>comprehension instead of a single map in the first solution). Maybe the 
>second's a little more readable (or a little less unreadable ;-).

Or if you prefer functional programming style (Only for 2.2):

def str_enum_dict(x):  return dict(zip(map(str, range(len(x))), x))
print "there %(1)s something %(0)s" % str_enum_dict(('there', 'is')) 

Huaiyu



More information about the Python-list mailing list