String Formatting in Python

From the Python cheat sheet · Strings & Formatting · verified Jul 2026

String Formatting

Format strings with f-strings, .format(), and % operator.

python
name = "Alice"
age = 30

# f-strings (Python 3.6+ — preferred)
f"Name: {name}, Age: {age}"
f"Next year: {age + 1}"
f"Price: {19.99:.2f}"

# Debug syntax (3.8+) — prints variable name and value
f"{name=}, {age=}"   # "name='Alice', age=30"

# .format()
"Name: {}, Age: {}".format(name, age)
💡 f-strings are the fastest and most readable — use them by default
⚡ The debug f"{x=}" syntax (3.8+) is gold for quick print debugging
📌 Format specs: :.2f (2 decimals), :, (thousands), :>10 (right-align)
🟢 Use r"..." raw strings for regex patterns and Windows file paths
stringsformattingf-strings

More Python tasks

Back to the full Python cheat sheet