Python - String Formatting
Overview
Estimated time: 25–35 minutes
Python offers multiple ways to format strings. This lesson builds a clear mental model for the str.format()
mini-language and modern f-strings, when to use each, and how to avoid common pitfalls.
Learning Objectives
- Use
f"..."
and"...".format()
to interpolate values safely and readably. - Apply the format mini-language for numbers, dates, alignment, and width/precision.
- Recognize security/perf pitfalls and choose the right approach for logging and internationalization.
Prerequisites
- Basics of variables, numbers, and strings
- Python 3.8+ recommended (examples note features requiring 3.10+ when applicable)
Examples
Prefer f-strings for most formatting: they are concise and fast.
name = "Ada"
age = 36
msg = f"{name} is {age} years old"
print(msg)
Expected Output:
Ada is 36 years old
Use :
to apply format specifiers:
pi = 3.14159
print(f"{pi:.2f}") # 2 decimal places
print(f"{pi:8.2f}") # width 8, aligned right
print(f"{pi:<8.2f}") # left align, width 8
Guidance & Patterns
- Contrast concatenation (
"Hello, " + name
) vs f-strings for readability and type-safety. - Show format specifiers: alignment (
< ^ >
), width, precision, type (d f x %
), thousands separators (,
). - Practice converting a poorly formatted print block into readable f-strings.
Best Practices
- Logging: Prefer lazy formatting via logger methods (e.g.,
logger.info("user=%s id=%s", user, id)
) or structured logs to avoid formatting cost when disabled. - Security: Never feed untrusted templates to
format()
or f-strings; avoideval
patterns. - i18n: Avoid concatenation; use placeholders compatible with translation tools.
Examples
from datetime import datetime
price = 1234.5
print(f"Price: ${price:,.2f}")
print("Hex: {:#x}".format(48879))
print(f"Now: {datetime(2024, 5, 17):%Y-%m-%d}")
Expected Output (approx):
Price: $1,234.50
Hex: 0xbeef
Now: 2024-05-17
Common Pitfalls
- For f-strings, expressions are evaluated immediately—do not include expensive calls repeatedly inside f-strings in hot loops.
- Be careful with
%
-formatting legacy style; prefer f-strings orstr.format
unless interacting with older code. - For
Decimal
, format with appropriate context to avoid float surprises.
Checks for Understanding
- How do you format a number with thousands separators and two decimals?
- When should you prefer logger parameterization over f-strings?
Show answers
f"{n:,.2f}"
- To avoid formatting cost when the log level disables the message and to keep logs structured.
Exercises
- Print a table with columns aligned: name, quantity, price. Use width and alignment specifiers.
- Format a datetime as
YYYY-MM-DD HH:MM
and as ISO 8601.