Skip to content
String Formatting
step 1/9

Reading — step 1 of 9

Learn

~3 min readWorking with Text

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:

python

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:

python

Format specs — the magic after :

Inside a {}, after a :, you can specify HOW the value is rendered.

Decimal places for floats

python

Width and alignment

python

Number padding and signs

python

Thousands separators

python

Currency and percentages

python

Hex / octal / binary

python

Aligning a column of values

python

Debug-style — = for self-labeling

A Python 3.8+ trick that's a lifesaver in print-debugging:

python

The = causes the f-string to print BOTH the expression text AND its value. No more print("x =", x) everywhere.

Common mistakes

  • Forgetting the f prefix: 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}" formats x to 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, but f"{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…

String Formatting — Python Fundamentals