[Python-ideas] new format spec for iterable types

Wolfgang Maier wolfgang.maier at biologie.uni-freiburg.de
Tue Sep 8 16:20:43 CEST 2015

On 08.09.2015 15:41, Oscar Benjamin wrote:
> The *{sep} surprised me until I tried
>      >>> '{x:.{n}f}'.format(x=1.234567, n=2)
>      '1.23'
> So format uses a two-level pass over the string for nested curly
> brackets (I tried a third level of nesting but it didn't work).

Yes, this is documented behavior

"A format_spec field can also include nested replacement fields within 
it. These nested replacement fields can contain only a field name; 
conversion flags and format specifications are not allowed. The 
replacement fields within the format_spec are substituted before the 
format_spec string is interpreted. This allows the formatting of a value 
to be dynamically specified."

> Unfortunately there's no way to also give a format string to the inner
> format call format(e) if I wanted to e.g. format those numbers in hex.

Right, that would require a much more complex format_spec definition. 
But the proposed simple version saves me from mistakenly writing:

'{}\t{}'.format(head, '\t'.join(data))

when some of the elements in data aren't strings and I should have written:

'{}\t{}'.format(head, '\t'.join(str(e) for e in data))

, a mistake that I seem to never learn to avoid :)

More information about the Python-ideas mailing list