Reading — step 1 of 9
Learn
Building strings that mix text and data is one of the most common tasks in programming. You've been doing it with concatenation and print commas — but both approaches get awkward fast. Imagine formatting a receipt with aligned columns, displaying currency with exactly two decimal places, or padding a leaderboard. That's where f-strings (formatted string literals) shine.
The three eras of Python string formatting
You'll see all three in real code, so it helps to recognize them:
All three produce the same output. Modern code uses f-strings for almost everything. They're concise, fast, and the variable references are right where they appear in the text.
f-string basics
Prefix a string with f (or F). Anything in {} is evaluated as Python:
Format specs — the magic after :
Inside a {}, after a :, you can specify HOW the value is rendered.
Decimal places for floats
Width and alignment
Number padding and signs
Thousands separators
Currency and percentages
Hex / octal / binary
Aligning a column of values
Debug-style — = for self-labeling
A Python 3.8+ trick that's a lifesaver in print-debugging:
The = causes the f-string to print BOTH the expression text AND its value. No more print("x =", x) everywhere.
Common mistakes
- Forgetting the
fprefix:print("{name}")prints the literal text{name}, not the variable's value. - Using single-quoted strings inside an f-string with single quotes:
f'{d['key']}'is a SyntaxError pre-3.12. Use a different quote style:f"{d['key']}". - Format spec confusion:
f"{x:.2f}"formatsxto 2 decimal places. The:separates the value from the format spec. No colon = no format spec. - Mixing f-string with .format() syntax:
f"{name:!r}"works, butf"{name}".format()is a sign you've confused the two systems.
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…