String Formatting
Master modern Python f-strings, expression interpolation, decimal precision specifiers, alignment formatting, and debugging shortcuts.
In earlier lessons, you combined text and numbers by manually calling str() and gluing pieces together with the + operator:
# The cumbersome, old-fashioned way:
name = "Maya"
score = 98
print("Hello " + name + ", your final score is " + str(score) + "/100.")
While that works, it is verbose, clunky to read, and prone to TypeError bugs if you forget a str() call.
Modern Python provides an elegant, expressive, and high-performance solution: Formatted String Literals, universally known as F-Strings.
1. The Anatomy of an F-String
Introduced in Python 3.6, an f-string is declared by placing the letter f (or F) immediately before the opening quotation mark:
name = "Maya"
score = 98
# The clean, modern Pythonic way:
print(f"Hello {name}, your final score is {score}/100.")
Output:
Hello Maya, your final score is 98/100.
Anything placed inside the curly braces { ... } is evaluated at runtime as a live Python expression. Python automatically handles type conversion for you—no manual str() calls required!
Expressions Inside F-Strings
You are not limited to simple variable names inside {}. You can evaluate any valid Python expression:
# Arithmetic inside braces:
width = 12
height = 5
print(f"Area: {width * height} sq ft") # Area: 60 sq ft
# String methods inside braces:
user = "alex"
print(f"Welcome, {user.capitalize()}!") # Welcome, Alex!
# Conditional (ternary) logic inside braces:
is_admin = True
print(f"Role: {'Administrator' if is_admin else 'Standard User'}")
2. Format Specifiers: Controlling How Data Looks
Often, raw data does not look visually appealing when printed. A price might print as 19.9 instead of $19.90, or a fraction might display 16 repeating decimal places.
In an f-string, you can add a format specifier after a colon (:) inside the braces:
$$\text{f”}{\text{expression} : \text{specifier}}\text{”}$$
Let’s look at the most useful format specifiers:
1. Decimal Precision (:.2f)
Rounds floating-point numbers to a specific number of decimal places:
raw_price = 19.999
tax_rate = 0.0825
total = raw_price * (1 + tax_rate)
print(total) # 21.6489175 (Messy raw float)
print(f"Total: ${total:.2f}") # Total: $21.65 (Clean 2-decimal currency)
2. Thousands Separators (:, and :_)
Automatically inserts commas or underscores into large numbers:
population = 8419600
national_debt = 34500000000000
print(f"City Population: {population:,}")
# City Population: 8,419,600
print(f"National Debt: ${national_debt:_}")
# National Debt: $34_500_000_000_000
3. Percentage Formatting (:.1%)
Automatically multiplies a decimal by 100 and appends a % sign:
accuracy = 0.94625
print(f"Model Accuracy: {accuracy:.1%}") # 94.6%
print(f"Model Accuracy: {accuracy:.2%}") # 94.63%
4. Zero-Padding (:0Nd)
Pads numbers with leading zeros to maintain fixed digit widths (essential for dates, serial numbers, and IDs):
order_id = 42
month = 3
day = 5
print(f"Order #{order_id:05d}") # Order #00042
print(f"Date: 2026-{month:02d}-{day:02d}") # Date: 2026-03-05
3. Alignment and Column Widths
When building terminal command-line interfaces or text reports, you often want data aligned neatly in vertical columns.
You can control horizontal alignment using:
<: Left-aligned (default for text)>: Right-aligned (default for numbers)^: Center-aligned
Follow the symbol with the total column character width:
# Format a clean mini-invoice table:
items = [
("Espresso", 3.50),
("Croissant", 4.25),
("Caramel Macchiato", 5.75)
]
print(f"{'Item':<20} | {'Price':>8}")
print("-" * 31)
for name, price in items:
print(f"{name:<20} | ${price:>7.2f}")
Output:
Item | Price
-------------------------------
Espresso | $ 3.50
Croissant | $ 4.25
Caramel Macchiato | $ 5.75
Notice how perfectly the vertical divider lines and price decimals align!
4. The Debugging Shortcut: {variable=}
Introduced in Python 3.8, adding an equals sign (=) after an expression inside an f-string automatically prints both the expression text and its resulting value:
latitude = 41.8781
longitude = -87.6298
# Instead of writing: f"latitude={latitude}, longitude={longitude}"
# Simply write:
print(f"{latitude=}, {longitude=}")
Output:
latitude=41.8781, longitude=-87.6298
You can even combine the = debug shortcut with format specifiers:
tax = 0.0825
print(f"{tax=:.1%}") # tax=8.2%
This is one of the fastest, most effective tricks for rapid debugging in production code.
5. Escaping Literal Braces
Because { and } have special meaning in f-strings, how do you print a literal curly brace character (such as when generating JSON or CSS text)?
Double the braces: {{ outputs {, and }} outputs }:
user_id = 901
json_string = f'{{"user_id": {user_id}, "status": "active"}}'
print(json_string)
# Output: {"user_id": 901, "status": "active"}
The Evolution of Python Formatting: A Historical Comparison
You will frequently encounter older Python codebases in the industry. Here is how formatting evolved across the language’s history:
| Method | Era Introduced | Syntax Example | Notes |
|---|---|---|---|
% Formatting | Python 1.0 (Legacy) | "%s has %d items" % (name, count) | C-style printf; error-prone with tuples |
str.format() | Python 2.6 / 3.0 | "{} has {} items".format(name, count) | Verbose; requires separating names from placeholders |
| F-Strings | Python 3.6 (Current) | f"{name} has {count} items" | Cleanest, fastest, and official industry standard |
Summary Checklist
- Prefix: Always prefix the string with
f"...". - Interpolation: Place any valid Python variable or expression inside
{}. - Precision: Use
:.2ffor two decimal places. - Commas: Use
:,for thousands separators (1,000,000). - Padding: Use
:02dfor leading zeros. - Alignment: Use
<(left),>(right), or^(center) with a column width. - Debugging: Use
{var=}to quickly print variable names and values.
Congratulations on completing Stage 3: Strings & Text Processing! You can now slice, clean, search, transform, and format text like a seasoned engineer.
Now, advance to Stage 4: Control Flow, where your programs learn to make smart decisions using conditions and loops.