Python Glossary Русский

Python 3.6+Strings (str)term

f-strings

formatting

f-strings (f'...') are formatted string literals. The expressions inside {} are evaluated at run time.

Syntax

f'{expr}'  |  f'{val:.2f}'  |  f'{val!r}'

A literal brace is written by doubling it: f'{{{x}}}' prints the value of x wrapped in braces. Before Python 3.12 an expression could not reuse the outer quote character or contain a backslash; PEP 701 lifted that, so older code full of helper variables was often shaped by the old restriction. Remember that an f-string interpolates the moment the literal is evaluated — it cannot be stored as a reusable template, that is what str.format() is for.

Examples

name = 'Alice'
print(f'Hello, {name}!')
# → 'Hello, Alice!'
x = 3.14159
print(f'{x:.2f}')
# → '3.14'
print(f'{2 ** 10}')
# → '1024'
n = 42
print(f'{n:>10d}')
# → '        42'
print(f'{n:010d}')
# → '0000000042'
s = 'hello'
print(f'{s!r}')
# → "'hello'"
width = 10
print(f'{"center":^{width}}')
# → center (выравнивание по центру, ширина 10)
val = 1234567.89
print(f'{val:,.2f}')
# → '1,234,567.89'

See also

Open in the full glossarydocs.python.orgReport an inaccuracy