f-strings (formatted string literals) let you embed expressions inside string literals by writing f"…" or F"…" and putting expressions in {}. They are the preferred way to format strings in Python 3.6+. They are readable, fast, and avoid the pitfalls of % and .format(). For other options see String formatting and String methods.

What they are

Prefix a string with f or F; inside the string, {expression} is evaluated and replaced by its string form. The expression can be a variable, a calculation, or a method call.

Basic usage

name = "Alice"
age = 30
message = f"My name is {name} and I'm {age} years old"
print(message)  # My name is Alice and I'm 30 years old

Expressions inside {}

Any valid Python expression can go inside the braces:

x, y = 5, 10
print(f"{x} + {y} = {x + y}")  # 5 + 10 = 15

name = "alice"
print(f"Hello, {name.upper()}!")  # Hello, ALICE!

Format specifiers: numbers and alignment

After the expression you can add :format_spec to control width, decimals, or percentage:

price = 19.99
print(f"Price: ${price:.2f}")   # Price: $19.99

ratio = 0.75
print(f"Progress: {ratio:.1%}")  # Progress: 75.0%

n = 42
print(f"Number: {n:05d}")       # Number: 00042

Multiline f-strings

Use triple-quoted f-strings for multiple lines. Newlines and indentation are preserved:

name, age = "Alice", 30
message = f"""
Name: {name}
Age: {age}
Status: Active
"""
print(message)

Why use f-strings

  • Readable: variable names appear where the value goes.
  • Flexible: any expression inside {}.
  • Efficient: often faster than % or .format().
  • Use f-strings for new code; see String formatting for legacy or special cases.

Next steps: Core Concepts · String formatting · String methods · Data types