New Python 3.0 string formatting - really necessary?

rdmurray at bitdance.com rdmurray at bitdance.com
Fri Dec 19 23:27:46 EST 2008


Quoth Steven D'Aprano <steve at REMOVE-THIS-cybersource.com.au>:
> Whether using % or format(), I don't see the need to change the code, 
> only the strings.
> 
> Using positional arguments is not really that different:
> 
> "{0} {1}".format("dead", "parrot")
> "{0} {1}".format("perroquet", "mort")

This should be something like:

_("{0} {1}").format(_("dead"), _("parrot"))

where il8n would substitute the template "{1} {0}" when doing French.

> versus:
> 
> "%s %s" % ("dead", "parrot")
> "%s %s" % ("perroquet", "mort")
> 
> In this case, the template on the left remains the same, you just have to 
> reorder the string arguments on the right. Clearly less satisfactory than 
> the solution using keyword substitution, but whatever solution you pick, 
> I don't see any advantage to format() over % formatting. Can you show an 
> example?

Not less satisfactory, but rather unworkable.  You can't do proper il8n
with %s formatting, since there is no way for the il8n machinery to
reorder the argument tuple.  It can only translate the template string.
So when doing il8n, the {} syntax wins out for brevity over the equivalent
% syntax (%s(somename)s).

Not that brevity is that important an argument.  The new system is just
so much more flexible than the old.  As someone else said, the design
is beautiful :)  I have a couple thousand lines of python code I wrote
a while back to layer on a system with this kind of flexibility...I was
shocked and pleased when I saw the PEP, since it echoed so many of the
ideas I had implemented in that code, plus more.  And all done better
of course :)

--RDM




More information about the Python-list mailing list