Mike Housky
Mike Housky

Reputation: 4069

Are nested format specifications legal?

Recently, I came across the following oddity. Nesting {}-enclosed format fields seems to work in both Python 2.7 and 3.6, but I can't find anything in the docs to say that should be so. For example, I get the following result on both 3.6 and 2.7:

>>> '{:{}.{}f}'.format(27.5, 6, 2)
' 27.50'

Has anyone seen this before, and is it an intended feature? Normally, I'd dismiss this as an implementation quirk, and maybe report it as a bug. Two things, though: Python docs don't always put all the information in the place I'd look for it, and this is a Very Nice Feature to have.

Upvotes: 15

Views: 1739

Answers (1)

jwodder
jwodder

Reputation: 57590

This is documented at the end of the introduction to the "Format String Syntax" section:

A format_spec field can also include nested replacement fields within it. These nested replacement fields may contain a field name, conversion flag and format specification, but deeper nesting is 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.

Some examples of this feature can also be found at the end of the "Format examples" section, such as:

>>> for align, text in zip('<^>', ['left', 'center', 'right']):
...     '{0:{fill}{align}16}'.format(text, fill=align, align=align)
...
'left<<<<<<<<<<<<'
'^^^^^center^^^^^'
'>>>>>>>>>>>right'
>>>

Upvotes: 17

Related Questions