Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 226
Mike Housky Avatar asked Jun 30 '18 01:06

Mike Housky


People also ask

What does __ format __ do in Python?

The __format__ method is responsible for interpreting the format specifier, formatting the value, and returning the resulting string. It is safe to call this function with a value of “None” (because the “None” value in Python is an object and can have methods.)

What are format specifiers in Python?

Python uses C-style string formatting to create new, formatted strings. The "%" operator is used to format a set of variables enclosed in a "tuple" (a fixed size list), together with a format string, which contains normal text together with "argument specifiers", special symbols like "%s" and "%d".

What is string format in Java?

In java, String format() method returns a formatted string using the given locale, specified format string, and arguments. We can concatenate the strings using this method and at the same time, we can format the output concatenated string. Syntax: There is two types of string format() method.


1 Answers

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'
>>>
like image 155
jwodder Avatar answered Oct 21 '22 11:10

jwodder