String Formatting (f-strings, format())
Python has several string formatting methods. f-strings (Python 3.6+) are the modern standard — fast, readable, and powerful.
15 min•By Priygop Team•Updated 2026
String Formatting
String Formatting
name = "Alice"
age = 25
price = 9.99
# 1. f-strings (RECOMMENDED — Python 3.6+)
print(f"Hello, {name}! Age: {age}")
print(f"Price: ${price:.2f}")
print(f"{'Centered':^20}") # center align
print(f"{'Left':<20}") # left align
print(f"{'Right':>20}") # right align
print(f"Binary: {42:b}") # 101010
print(f"Hex: {255:x}") # ff
print(f"Percentage: {0.756:.1%}") # 75.6%
# 2. .format() method
print("Hello, {}! Age: {}".format(name, age))
print("{0} is {1} years old".format(name, age))
print("{name} is {age}".format(name="Bob", age=30))
# 3. % formatting (legacy C-style)
print("Hello, %s! Age: %d" % (name, age))
print("Price: %.2f" % price)
# Multi-line f-strings
report = f"""
=== Report ===
Name: {name}
Age: {age}
Price: ${price:.2f}
==============
"""
print(report)Tip
Tip
f-strings support format specs: {price:.2f} for decimals, {name:>20} for alignment, {num:,} for thousand separators, {pct:.1%} for percentages.
Diagram
Loading diagram…
f-strings > .format() > %. Use = for debug output. :, for thousands separator. :.2f for decimals.
Common Mistake
Warning
Using + to build strings from mixed types fails. 'Age: ' + 25 raises TypeError. Use f'Age: {25}' instead.
Practice Task
Note
(1) Format a price table with aligned columns. (2) Display numbers with thousand separators. (3) Create a multi-line report with f-strings.