New Python 3.0 string formatting - really necessary?

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Sat Dec 20 04:07:49 CET 2008


On Fri, 19 Dec 2008 17:12:00 -0800, r wrote:

> Why move away from a concise and widely accepted way of sting
> formatting, just to supposedly make it a little easier for n00bs? (which
> i disagree this is easier) In turn, creating more syntactical clutter.
> (%s %f %d) is all you need to remember. If people can't understand that,
>  i fear for the future of Humans as a species!

Reading your wibbling, so do I. Take ten deep breaths and calm down. 

Firstly, the introduction of format() is not to "make it a little easier 
for n00bs" as you claim, but to allow more powerful, flexible string 
formatting.

Secondly, to use % formatting to full effectiveness you need to know MUCH 
more than (%s %f %d). You need to know:

Formatting codes: %s %r %d %f %g %G %c %i %u %o %x %X %e %E %%
(have I missed any?)
Keyword formatting: %(name)s
Flags: - + 0
Field width and precision, including the special case of "*"

and how they fit together:

%[(name)][flags][width][.precision][unused(!) length modifier]code


You also need to know about operator precedence:

>>> "%s" % 3+2
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: cannot concatenate 'str' and 'int' objects

and the special casing of tuples:

>>> "Tuple = %s" % (1,2,3)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: not all arguments converted during string formatting



For trivial cases, format() isn't much harder than %:

"{0}".format(x)
"%s" % x

For more complex cases, format() will let you do things that you can't do 
with only %, e.g. arbitrary fill characters, centring fields, percentage 
formatting, mixing positional and keyword arguments, etc.

Before you blow yet another gasket, go read the PEP:

http://www.python.org/dev/peps/pep-3101/


-- 
Steven



More information about the Python-list mailing list