[Python-3000] String formating operations in python 3k
skip at pobox.com
skip at pobox.com
Mon Apr 3 22:37:21 CEST 2006
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:
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",
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
pest = current_plague()
print "my %(pet)s has %(pest)s".format(pet="dog", **locals())
That is, mix keyword-style and dict-style parameter passing. The above is a
lame example, but I occasionally find myself creating single-use local
variables to hold arithmetic expressions I want to display. Computing the
expression to be expanded in the function call would be cleaner.
If I have my keyword mappings in multiple dictionaries might something like
"my %(pet)s has %(pest)s".format(**pets, **pests)
be supported? That reminds me of the debate about adding to dictionaries:
how are duplicate keys handled? Multiple occurrences of **dict
aren't supported in Python 2.4. I suppose it probably doesn't typically
make a lot of sense, but for this it seems like it might be reasonable.
More information about the Python-3000