Python Glossary Русский

all Python 3Built-in functionsterm

format

strings

Formats a value according to a format specification string (format spec). Calls the object's __format__ method.

Syntax

format(value, format_spec='')

This is precisely what happens inside the braces of an f-string, so a separate call earns its keep only when the spec itself is computed at runtime — say, the number of decimals comes from a variable. Do not mix it up with the str.format() method: here the first argument is the value being formatted, not a template. Rounding for '.2f' follows the binary float value, which is why format(2.675, '.2f') honestly yields 2.67.

Examples

print(format(3.14159, '.2f'))  # → 3.14
print(format(42, '08b'))  # → 00101010
print(format(1000000, ','))  # → 1,000,000
print(format('hello', '^10'))  # →   hello
print(format(0.25, '%'))  # → 25.000000%

See also

Open in the full glossarydocs.python.orgReport an inaccuracy