f-strings
- Version
- 3.14
- Since
- 3.6
- Review
- Draft
Summary#
An f-string evaluates the expressions inside its braces and inserts the formatted results. A format specifier after : controls width, alignment, precision and number style.
Syntax#
f"{value}"
f"{value!r}"
f"{value:>10,.2f}"
f"{value=}"
Example#
name = "Mai"
total = 1234567.5
ratio = 0.4567
count = 42
width = 8
print(f"{name!r} owes {total:,.2f}")
print(f"{ratio:.1%}|{name:<6}|{name:>6}|")
print(f"{count=} {count:05d} {count:#x}")
print(f"[{name:^{width}}] {{literal braces}}")
Expected output#
'Mai' owes 1,234,567.50
45.7%|Mai | Mai|
count=42 00042 0x2a
[ Mai ] {literal braces}
Common mistakes#
An f-string is evaluated immediately where it appears. Storing it before a variable changes does not update the result, and it cannot serve as a reusable template. Put the f-string inside a function, or use str.format with a stored template. Write doubled braces to produce literal braces.
Version applicability#
f-strings were added in Python 3.6. The = debug specifier requires Python 3.8. Python 3.12 allows quotes of the enclosing kind, backslashes and comments inside replacement fields; earlier versions reject quote reuse with a SyntaxError.
Sources#
- Attribution
- DevLookup contributors
- License
- CC-BY-4.0