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

Python String Formatting

String formatting is about building neat sentences out of pieces, like filling in a form letter with each person's name. Python has several ways to do it, from old to new.
Syntax
python
"text %s and %d" % (string_value, integer_value)
"text {}".format(value)
f"text {variable}"

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))  # %s and %d are old-style C-like format specifiers

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))  # legacy % formatting
print("{} is {}".format(name, age))  # .format() method
print(f"{name} is {age}")  # f-string, the modern recommended style

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")  # $name-style placeholders instead of {} or %s
print(t.substitute(name="Alex", age=30))  # fill placeholders by keyword

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!
"""  # triple-quoted f-string spans multiple lines
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
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Passing a single tuple value to % without wrapping it, as in "%s" % (1, 2), which raises TypeError; use "%s" % ((1, 2),).
  2. Using the wrong specifier, like "%d" % "5", which raises TypeError.
  3. Giving the wrong number of values to %, e.g. two %s with one argument, which raises TypeError: not enough arguments.

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.