← Back to Python Course | Chapter 2: Input, Output & Operators | Lesson 5 of 16

Python String Formatting

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

python
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

python
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

python
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

python
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

python
name = "Alex"
print(f"{name} formatted with an f-string")
# Use string.Template instead when the template itself comes from untrusted input

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.