python - What is global format() function meant for? -


there str.format() method in python familiar not work same way format() function (global-builtin).

what purpose of global format() function?

the format() function formats one value according formatting specification.

the str.format() method parses out template, , formats individual values. each {value_reference:format_spec} specifier applied matched value using format() function, format(referenced_value, format_spec).

in other words, str.format() built on top of format() function. str.format() operates on full format string syntax string, format() operates on matched values , applies format specification mini-language.

for example, in expression

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

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

use format() function when want format single value, use str.format() when want place formatted value in larger string.

under hood, format() delegates object.__format__ method let value interpret formatting specification. str.format() calls method directly, you should not rely on this. object.__format__ hook, in future format() might apply more processing result of hook, or pre-process format pass in. implementation detail really, interesting if want implement own formatting language object type.

see pep-3101 advanced string formatting original proposal added str.format(), format() , object.__format__ hook language.


Comments

Popular posts from this blog

Hatching array of circles in AutoCAD using c# -

ios - UITEXTFIELD InputView Uipicker not working in swift -

Python Pig Latin Translator -