% formatting (old style)

name = "Alice"
age = 30

message = "My name is %s and I'm %d years old" % (name, age)
print(message)  # "My name is Alice and I'm 30 years old"

.format() method

name = "Alice"
age = 30

# Positional:
message = "My name is {} and I'm {} years old".format(name, age)

# Named:
message = "My name is {name} and I'm {age} years old".format(name=name, age=age)

f-strings (modern, recommended)

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"

# With expressions:
message = f"Next year I'll be {age + 1}"

Which to use?

  • f-strings: Python 3.6+, most readable, fastest
  • .format(): Python 2.7+, more flexible than %
  • %: Old style, still works but not recommended

Formatting numbers

price = 19.99

# f-string with formatting:
print(f"Price: ${price:.2f}")  # "Price: $19.99"

# .format() with formatting:
print("Price: ${:.2f}".format(price))