f-strings in Python: format values into text
An f-string embeds values inside text, and a format spec after a colon controls exactly how each value looks — perfect for a HUD line or a clean report.
The big idea
An f-string (f"...") evaluates {expressions} inside the text, and {value:spec} formats how that value is rendered.
See it in code
An f-string evaluates {expressions} inside the text. Drop the score and lives straight into a HUD line:
score = 1200
lives = 3
print(f"SCORE {score} LIVES {lives}")SCORE 1200 LIVES 3
Each { } was replaced by its value. That's the whole idea — text and variables, together.
After a colon, a format spec controls how a value looks. {accuracy:.1%} renders a fraction as a percent with one decimal:
accuracy = 0.8734
print(f"Accuracy: {accuracy:.1%}")Accuracy: 87.3%
.1% did two jobs: multiply by 100 and round to one decimal. Next we'll add alignment and build the full scoreboard.
A scoreboard needs embedding, rounding, and alignment. {accuracy:.1%} formats the percent, and {score:>8} right-aligns the number in a field 8 characters wide so columns line up:
score = 1200
lives = 3
accuracy = 0.8734
print(f"SCORE {score} LIVES {lives}")
print(f"Accuracy: {accuracy:.1%}")
print(f"{score:>8}")SCORE 1200 LIVES 3
Accuracy: 87.3%
1200The format spec after the colon is a mini-language: .1% means 'percent, one decimal'; >8 means 'right-align in width 8'. {0.8734:.1%} became 87.3% just as in the warm-up, and the padded 1200 lines up under a column heading.
Formatted text is everywhere output matters: f"${price:,.2f}" for money, f"{pct:.0%}" for a progress bar, f"{name:<12}" to build a table. f-strings also make great debug lines — f"{x=}" prints x=240, the name and value together.
Try it yourself
Format accuracy as .2% and watch the extra digit appear. Then build a two-column table by padding a label with {label:<10} and a number with {n:>6} on each line.
The common mistake
Putting a stray quote or brace inside the braces. f"{name's score}" breaks, and to print a literal brace you must double it: f"{{literal}}" renders {literal}. Keep the expression inside { } simple — compute complex things beforehand.
What it unlocks
Clean formatting elevates print output, pairs with string methods, and renders the score and lives on a game HUD.