[Python-ideas] String formatting and namedtuple

Guido van Rossum guido at python.org
Fri Feb 13 19:01:19 CET 2009


On Fri, Feb 13, 2009 at 6:19 AM, Antoine Pitrou <solipsis at pitrou.net> wrote:
> Guido van Rossum <guido at ...> writes:
>>
>> I don't intend to force the issue. I'm disappointed though --
>> .format() fixes several common stumbling blocks with %(name)s and at
>> least one with %s.
>
> Everytime I try to experiment a bit with format codes, I find them unintuitively
> complex:
>
>>>> "{0!r}".format(2.5)
> '2.5'
>>>> "{0:r}".format(2.5)
> Traceback (most recent call last):
>  File "<stdin>", line 1, in <module>
> ValueError: Unknown conversion type r
>>>> "{0!f}".format(2.5)
> Traceback (most recent call last):
>  File "<stdin>", line 1, in <module>
> ValueError: Unknown conversion specifier f
>>>> "{0:f}".format(2.5)
> '2.500000'
>
> Why must the 'f' code be preceded by a colon rather than by an exclamation mark?

Actually, !r is the exception. The rule is that a colon is followed by
a formatting language specific to type type, e.g. {:f} (which is only
supported by floating point numbers and means fixed-point), whereas an
exclamation point is followed by a single letter that bypasses the
type-specific formatting -- {!r} is really the only one you need to
learn.

> There is surely a rational explanation, but in day-to-day use it is really
> confusing. Add to this the annoyance of typing ".format" and of adding curly
> braces everywhere, and "%" is clearly handier despite the lonely tuple problem.

It is true that the advantages of .format() are probably more
appreciated when you are writing a larger program.

-- 
--Guido van Rossum (home page: http://www.python.org/~guido/)



More information about the Python-ideas mailing list