Tutorial
Python f-strings — formatting numbers and text cleanly
Master f-string interpolation, thousands separators, fixed decimals, and why they beat old %-style formatting for everyday code.
March 2026 · 6 min read · 13 views · 0 hearts
What is an f-string?
Since Python 3.6, f-strings (f"...") let you interpolate variables and expressions directly inside a string.
They are usually the clearest choice for formatting user-visible text.
Interpolation
Variables inside curly braces are evaluated when the string is created:
user = "sam"
points = 42
msg = f"{user} scored {points} points today."
print(msg)
Number formatting
After an expression, add a colon and a format specifier. Common patterns include grouping thousands, fixed decimal places, and zero-padding.
population = 8_021_000_000
print(f"Rough population: {population:,}")
ratio = 22 / 7
print(f"Pi-ish: {ratio:.4f}")
Debugging helpers
Python 3.8+ supports f"{expr=}" which prints both the expression text and its value — handy while iterating locally.
limit = 25
print(f"{limit=}")
Compared to older styles
str.formatis still fine for templates or translated strings.%formatting exists mainly in legacy code.- For everyday diagnostics and logs, f-strings tend to win on readability.
Try it yourself
Open the IDE sample linked above — tweak names, precision, and grouping — then extend the snippet with your own variables.
Sponsored
Comments
Questions, corrections, and tips stay visible for everyone reading this page.
Join the discussion
Replies