[Python-ideas] Customizing format()

Terry Reedy tjreedy at udel.edu
Wed Mar 18 22:27:08 CET 2009

Raymond Hettinger wrote:
>>> # DE and US dicts as per Raymond's format() example
>>> fmt = "The value is {:,.5f}{!conv}"
>> A new conversion specifier should follow the current pattern and be a 
>> single letter, such as 'c' for 'custom' or 'd' for dict.
>> If, as I would expect, str.format scans left to right and interprets 
>> and replaces each field spec as it goes, then the above would not 
>> work. So put the conversion field before the fields it applies to.
> My interpretation is that the conv-dictionary applies to the whole
> string (not field-by-field) 

That was not specified.  If so, then a statement like
"""A number such as {0:15.2f} can be formatted many ways:
USA: {0:15,.2f), EU: {0:15<whatever>f},
India: {0:15<whatever>f), China {0:15<whatever>f)"
would not be possible.

Why not allow extra flexibility?  Unless the conversion is set by 
setting a global variable ala locale, the c-dict will be *used* 
field-by-field in each call to ob.__format__(fmt, conv), so there is no 
reason to force each call in a particular series to use the same conversion.

 > and that it can go at the end (because
> it doesn't affect parsing, rather it applies to the translation phase).

We agree that parsing out the conversion spec must happen before the 
translation it affects.  If, as I supposed  above (because of how I 
would think to write the code), parsing and translation are intermixed, 
then parsing the spec *after* translation will not work.

Even if they are done in two batches, it would still be easy to rebind 
the c-dict var during the second-phase scan of the replacement fields.

Terry Jan Reedy

More information about the Python-ideas mailing list