Interpolating a string

Python:
Interpolating a string

How to:

In Python 3.6 and above, you can interpolate strings using f-strings. Here’s how:

name = 'Alice'
age = 30
greeting = f"Hello, {name}. You are {age} years old."

print(greeting)

Output:

Hello, Alice. You are 30 years old.

You can also use expressions inside the curly braces:

a = 5
b = 10
info = f"Five plus ten is {a + b}, not {2 * (a + b)}."

print(info)

Output:

Five plus ten is 15, not 30.

Deep Dive

Before Python 3.6, .format() was the way to go for interpolating strings:

name = 'Bob'
age = 25
greeting = "Hello, {}. You are {} years old.".format(name, age)

print(greeting)

Old school Python (versions < 2.6) used the % operator for interpolation, which is less intuitive and can get messy with multiple variables:

name = 'Carol'
age = 35
greeting = "Hello, %s. You are %d years old." % (name, age)

print(greeting)

Besides cleaner syntax, f-strings are faster because they are evaluated at runtime and then converted directly into an efficient string format operation. The .format() and % operator involve more steps and are slower.

See Also