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
- PEP 498 – Literal String Interpolation for official documentation on f-strings.
- Python f-strings by Real Python for a tutorial on using f-strings.
- The .format() Method in the Python documentation to understand the older
.format()
method of string formatting.