Python Fundamentals
String Formatting
Concatenating strings with + gets messy fast, especially mixing types:
Jr Codex Python Notes
Level: Beginner Prerequisites: Chapter 4 Time to complete: ~20 minutes
Table of Contents
- Why Formatting Matters
- f-strings (the Modern Standard)
- Formatting Numbers
- The
.format()Method - Old-Style
%Formatting - Which Style Should You Use?
- Summary & Next Steps
1. Why Formatting Matters
Concatenating strings with + gets messy fast, especially mixing types:
name = "Alice"
age = 25
# Clunky and error-prone
message = "Name: " + name + ", Age: " + str(age)Python gives you three ways to embed values into strings. This chapter covers all three, but you'll mostly use the first one.
2. f-strings (the Modern Standard)
Introduced in Python 3.6, f-strings are the preferred way to format strings today. Prefix the string with f and embed expressions in {}.
name = "Alice"
age = 25
message = f"Name: {name}, Age: {age}"
print(message) # Name: Alice, Age: 25You can put any valid expression inside {}, not just variable names:
a, b = 5, 3
print(f"{a} + {b} = {a + b}") # 5 + 3 = 8
user = {"name": "Bob"}
print(f"Hello, {user['name']}!") # Hello, Bob!
def shout(text):
return text.upper()
print(f"{shout('hi')}") # HIDebugging with = (Python 3.8+)
x = 42
print(f"{x=}") # x=42 — prints both the expression and its value, great for quick debugging3. Formatting Numbers
f-strings support a format spec after a colon — this is where most of the day-to-day power lives:
price = 1234.5678
pi = 3.14159265
print(f"{price:.2f}") # 1234.57 — 2 decimal places
print(f"{price:,.2f}") # 1,234.57 — thousands separator + 2 decimals
print(f"{pi:.3f}") # 3.142 — 3 decimal places
count = 7
print(f"{count:03d}") # 007 — zero-padded to 3 digits
ratio = 0.4567
print(f"{ratio:.1%}") # 45.7% — percentage formatting
print(f"{42:>8}") # " 42" — right-align in 8-char width
print(f"{42:<8}|") # "42 |" — left-align
print(f"{42:^8}|") # " 42 |" — center-align| Spec | Meaning | Example |
|---|---|---|
.2f | Fixed-point, 2 decimals | 3.14159 → 3.14 |
, | Thousands separator | 1234567 → 1,234,567 |
03d | Zero-pad integer to width 3 | 7 → 007 |
.1% | Percentage, 1 decimal | 0.457 → 45.7% |
>, <, ^ | Align right/left/center | see above |
4. The .format() Method
Predates f-strings (Python 2.7+) and is still common in older codebases:
name = "Alice"
age = 25
print("Name: {}, Age: {}".format(name, age)) # positional
print("Name: {n}, Age: {a}".format(n=name, a=age)) # named
print("{0} is {1}. {0} lives here.".format(name, age)) # indexed, reusable
print("{:.2f}".format(3.14159)) # 3.14 — same format specs as f-strings5. Old-Style % Formatting
The oldest style, inherited from C's printf. You'll mainly recognize it when reading legacy code:
name = "Alice"
age = 25
print("Name: %s, Age: %d" % (name, age)) # Name: Alice, Age: 25
print("Pi is %.2f" % 3.14159) # Pi is 3.14| Specifier | Type |
|---|---|
%s | String |
%d | Integer |
%f | Float |
6. Which Style Should You Use?
Recommendation:
──────────────────────────────────────────────
New code → f-strings (fastest, most readable)
Reading legacy code → recognize .format() and %-formatting
Logging templates → sometimes %-style (deferred evaluation,
e.g. logging.info("%s", value))
──────────────────────────────────────────────
All three examples below produce the identical output — but only the first is recommended for new code:
name, age = "Alice", 25
print(f"{name} is {age}") # ✓ preferred
print("{} is {}".format(name, age)) # acceptable, older codebases
print("%s is %d" % (name, age)) # legacy, avoid in new code7. Summary & Next Steps
Key Takeaways
- f-strings (
f"{expr}") are the modern standard — readable, fast, support inline expressions and format specs. - Format specs (
:.2f,:,,:03d,:.1%) control decimals, separators, padding, and percentages. .format()and%-formatting still appear in real (often older) codebases — recognize them even if you don't write new code with them.
Concept Check
- Rewrite
"Total: " + str(total)as an f-string. - What does
f"{value:.2f}"do tovalue = 3.14159? - What's the output of
f"{7:03d}"?
Next Chapter
Jr Codex — 1-on-1 Personalized Coaching | Back to Module Index