Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is global format() function meant for?

There is the str.format() method in python which I am familiar with however it does not work the same way as the format() function (global-builtin).

What is the purpose of the global format() function?

like image 580
Har Avatar asked Jun 04 '26 01:06

Har


1 Answers

The format() function formats one value according to a formatting specification.

The str.format() method parses out a template, and then formats individual values. Each {value_reference:format_spec} specifier is basically applied to the matched value using the format() function, as format(referenced_value, format_spec).

In other words, str.format() is built on top of the format() function. str.format() operates on a full Format String Syntax string, format() operates on the matched values and applies just the Format Specification Mini-Language.

For example, in the expression

'The hex value of {0:d} is {0:02x}'.format(42)

the template string has two template slots, both formatting the same argument to the str.format() method. The first interpolates the output of format(42, 'd'), the other format(42, '02x'). Note that the second argument in both cases is the format specifier, e.g. everything that comes after the : colon in the template placeholder.

Use the format() function when you want to format just a single value, use str.format() when you want to place that formatted value in a larger string.

Under the hood, format() delegates to the object.__format__ method to let the value itself interpret the formatting specification. str.format() calls that method directly, but you should not rely on this. object.__format__ is a hook, in future format() might apply more processing to the result of that hook, or pre-process the format to pass in. This is all an implementation detail really, only interesting if you want to implement your own formatting language for your object type.

See PEP-3101 Advanced String Formatting for the original proposal that added str.format(), format() and the object.__format__ hook to the language.

like image 158
Martijn Pieters Avatar answered Jun 06 '26 16:06

Martijn Pieters



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!