Python String Formatting
In this page:
Legacy % Formatting
The % operator is Python's oldest string-formatting mechanism, inherited from C's printf style — "%s is %d" % (name, age) — and while it still works, it has largely been superseded by newer, more readable options.
Example: Legacy % Formatting
name = "Alex"
age = 30
print("%s is %d" % (name, age))
Comparing Format Styles
Python offers three formatting approaches with overlapping purposes: % formatting (legacy, C-style), .format() (more flexible, introduced in Python 2.6), and f-strings (the newest and generally fastest, since Python 3.6). For new code, f-strings are the recommended default.
Example: Comparing Format Styles
name, age = "Alex", 30
print("%s is %d" % (name, age))
print("{} is {}".format(name, age))
print(f"{name} is {age}")
Template Strings
The string.Template class uses $name-style placeholders instead of braces or percent signs, and is specifically designed to be safer when the template itself might come from an untrusted source, since it doesn't support arbitrary expression evaluation like f-strings do.
Example: Template Strings
from string import Template
t = Template("$name is $age")
print(t.substitute(name="Alex", age=30))
Multi-line String Formatting
Triple-quoted strings can span multiple lines and still be formatted normally, which makes them convenient for embedding multi-line SQL queries, HTML fragments, or configuration blocks directly in Python code without awkward line-by-line concatenation.
Example: Multi-line String Formatting
name = "Alex"
message = f"""
Hello {name},
Welcome!
"""
print(message)
String Formatting Best Practices
F-strings are the right default for most formatting because they're fast and easy to read; reach for string.Template specifically when the format string itself is user-supplied, since evaluating untrusted f-string-style expressions would be a security risk.
Example: String Formatting Best Practices
name = "Alex"
print(f"{name} formatted with an f-string")
# Use string.Template instead when the template itself comes from untrusted input
Chapter Quiz — Complete all 16 topics to unlock
0/16 topics done
Complete these topics first:
- Python print()
- Python input()
- Python Format Strings
- Python f-strings
- Python String Formatting
- Python Arithmetic Operators
- Python Relational Operators
- Python Logical Operators
- Python Bitwise Operators
- Python Assignment Operators
- Python Increment & Decrement
- Python Ternary Operator
- Python Operator Precedence
- Python Identity Operators
- Python Membership Operators
- Python Operators