[Python-3000] String formating operations in python 3k

Georg Brandl g.brandl at gmx.net
Mon Apr 3 22:40:49 CEST 2006


skip at pobox.com wrote:
> I sort of lost track of the thread, then noticed a recent message where
> Guido seems to be cozying up to the idea, so I thought maybe I ought to
> think about it for a few minutes.  As far as I can tell, the proposal is:
> 
>     usage               example
>     s.format(x, y)      simple % substition, e.g.
>                         "my %s has %s".format("dog", "fleas")
>     s.format(**x)       named substitution using dictionaries, e.g.
>                         pet = "kangaroo"
>                         pest = "marmots"
>                         "my %(pet)s has %(pest)s".format(**locals())
>     s.format(key=val)   named substitution using keyword args, e.g.
>                         "my %(pet)s has %(pest)s".format(pet="armadillo",
>                                                          pest="texans")
> 
> One thing that's always been a bit cumbersome for me with the current mod
> operator syntax is that it's all or nothing.  I either have to cram
> everything into a single dictionary, hack up some sort of multimap, or fall
> back to simple substitution.  With str.format(), I could presumably do
> something like
> 
>     pest = current_plague()
>     if pest:
>         print "my %(pet)s has %(pest)s".format(pet="dog", **locals())

You can do that right now, using

print "my %(pet)s has %(pest)s" % dict(pet="dog", **locals())

Georg



More information about the Python-3000 mailing list