Python — String Formatting
f-strings — the modern standard
Prefix with f, drop values into {}:
name = "Ada"
age = 36
print(f"Hello {name}, you are {age}")
Braces run ANY expression:
f"Next year: {age + 1}"
f"Loud: {name.upper()}"
f"Status: {'adult' if age >= 18 else 'minor'}"
The mini-language after the colon
pi = 3.14159265
f"{pi:.2f}" # "3.14" 2 decimal places
f"{1234567:,}" # "1,234,567" thousands separators
f"{0.256:.1%}" # "25.6%" percentages!
f"{42:05d}" # "00042" zero-padded width 5
| Specifier | Effect |
|---|---|
.Nf | N decimals |
:, | comma grouping |
:.1% | percent |
05d | pad to width 5 with zeros |
>10 / <10 / ^10 | align right/left/center in width 10 |
Alignment tables
for item, price in [("Keyboard", 80), ("Cable", 9.5)]:
print(f"{item:<12}{price:>8.2f}")
# Keyboard 80.00
# Cable 9.50
< > ^ plus a width — instant clean columns.
Debugging shortcut (3.8+)
f"{name=}, {age=}"
# name='Ada', age=36 ← variable name AND value, one line
Legendary for quick console diagnosis.
Multiline & escaping
// python:
msg = f"""User {name}
Total: {price * qty:.2f}"""
print(f"{{literal braces}}") # double them
Older styles — recognize, don't start
"Hello %s" % name # printf-era
"{} is {}".format(name, age) # pre-3.6 workhorse
"Hi %(name)s" % {"name": "Ada"} # dict mapping
You'll meet all three in tutorials and legacy code; new code uses f-strings.
Formatting dates inside f-strings
from datetime import datetime
f"Today is {datetime.now():%A, %B %d}" # methods AND format specs compose
f"Log at {datetime.now():%H:%M:%S}"
Mini Practice
- Receipt printer: three items aligned to two columns.
- Percentage formatter for a 0–1 score.
- Zero-padded clock from h/m/s ints.
{var=}debug five variables at once.- Convert one %s-style legacy string to an f-string.
Next: file open →
Related Topics
Frequently Asked Questions about String Formatting
What is String Formatting in Python?
String Formatting is a fundamental concept in Python. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn String Formatting?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn String Formatting.
Why is String Formatting important in Python?
String Formatting is essential for Python development. Understanding this concept will help you write better code and solve real-world problems more effectively.