Python Glossary Русский

all Python 3Strings (str)term

format() — the formatting method

formatting

The str.format() method substitutes arguments by position or by name. It supports format specifiers.

Syntax

'{}'.format(val)  |  '{name}'.format(name=val)  |  '{:.2f}'.format(num)

Literal braces are escaped by doubling them: {{ and }}. You cannot mix automatic numbering {} with explicit indexes {0} in one template — that raises ValueError. F-strings are the default for new code; format() earns its place when the template comes from outside the source (config, translation file) — and for that same reason never format a template supplied by a user: constructs like {0.__class__} can walk into the object's internals.

Examples

print('{} {}'.format('Hello', 'World'))
# → 'Hello World'
print('{0} {1} {0}'.format('ha', 'ho'))
# → 'ha ho ha'
print('{name} is {age}'.format(name='Alice', age=30))
# → 'Alice is 30'
print('{:.2f}'.format(3.14159))
# → '3.14'
print('{:>10}'.format('hi'))
# → '        hi'
print('{:0>5}'.format(42))
# → '00042'
print('{:,}'.format(1000000))
# → '1,000,000'

See also

Open in the full glossarydocs.python.orgReport an inaccuracy