[Tutor] String Replacement question

wesley chun wescpy at gmail.com
Thu May 22 20:25:48 CEST 2008


> >  some = 'thing'
> >  print '%s %s %s %s' % (some,some,some,some)
>
> You can use named parameters, which moves the repetition to the format string:
>
>  In [24]: print '%(some)s %(some)s %(some)s %(some)s' % (dict(some=some))
>  thing thing thing thing
>
>  With multiple values, a common trick is to pass vars() or locals() as
>  the dict, giving the format access to all defined variables:
>
>  In [27]: a=1
>  In [28]: b=2
>  In [29]: print '%(a)s %(b)s' % vars()
>  1 2


everyone has clever solutions on the repeating, but as kent has shown
in his example above, i think a dictionary form of the string format
operator is the best solution.

once you have the dictionary, you can add many more repetitions in
your format string without touching the dictionary argument on the
RHS, unlike using the tuple solution where you would have to update a
multiplier. it's also works better if you have multiply-repeated
variables... you don't have to create another variable on the right
along with a multiplier.  somewhere you just have to add it to the
dict just once.

cheers,
-- wesley
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
"Core Python Programming", Prentice Hall, (c)2007,2001
    http://corepython.com

wesley.j.chun :: wescpy-at-gmail.com
python training and technical consulting
cyberweb.consulting : silicon valley, ca
http://cyberwebconsulting.com


More information about the Tutor mailing list