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.
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.)
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".
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.
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'
>>>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With