What Are f-Strings?
f-strings (formatted string literals) let you embed expressions directly inside string literals, prefixed with f:
name = "Alice"
age = 30
print(f"My name is {name} and I am {age} years old.")
# My name is Alice and I am 30 years old.
Introduced in Python 3.6, f-strings are the preferred way to format strings.
Expressions Inside Braces
You can put any valid Python expression inside the curly braces:
print(f"2 + 2 = {2 + 2}") # 2 + 2 = 4
print(f"{'hello'.upper()}") # HELLO
print(f"{len([1, 2, 3])}") # 3
Number Formatting
f-strings support format specifiers after a colon:
pi = 3.14159265
print(f"{pi:.2f}") # 3.14 (2 decimal places)
print(f"{1000000:,}") # 1,000,000 (thousands separator)
print(f"{0.85:.0%}") # 85% (percentage)
print(f"{42:08d}") # 00000042 (zero-padded)
Alignment and Padding
name = "Python"
print(f"{name:<20}") # Python (left-aligned)
print(f"{name:>20}") # Python (right-aligned)
print(f"{name:^20}") # Python (centered)
print(f"{name:*^20}") # *******Python******* (centered with fill)
Debugging with =
Python 3.8 added the = specifier for quick debugging:
x = 42
y = "hello"
print(f"{x = }") # x = 42
print(f"{y = }") # y = 'hello'
print(f"{x + 1 = }") # x + 1 = 43
When to Use Other Methods
f-strings are best for most cases. Use str.format() when you need to reuse a template, or % formatting when working with logging (which uses % style internally).