Are nested format specifications legal?

  • A+

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.


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' >>> 


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: