Last modified: Feb 08, 2025 By Alexander Williams
Python String Interpolation: A Complete Guide
String interpolation is a powerful feature in Python. It allows you to embed variables and expressions directly into strings. This makes your code cleaner and more readable.
In this guide, we'll explore the three main methods of string interpolation in Python: f-strings, format(), and %-formatting. We'll also provide examples to help you understand each method.
1. f-strings (Formatted String Literals)
Introduced in Python 3.6, f-strings are the most modern and preferred way to interpolate strings. They are easy to read and write.
name = "Alice"
age = 30
greeting = f"Hello, my name is {name} and I am {age} years old."
print(greeting)
Output: Hello, my name is Alice and I am 30 years old.
In the example above, the variables name
and age
are embedded directly into the string using curly braces {}
.
2. The format() Method
The format()
method is another way to interpolate strings. It is available in Python 2.6 and later.
name = "Bob"
age = 25
greeting = "Hello, my name is {} and I am {} years old.".format(name, age)
print(greeting)
Output: Hello, my name is Bob and I am 25 years old.
Here, the format()
method replaces the placeholders {}
with the values of name
and age
.
3. %-formatting
%-formatting is the oldest method of string interpolation in Python. It is similar to the printf-style formatting in C.
name = "Charlie"
age = 35
greeting = "Hello, my name is %s and I am %d years old." % (name, age)
print(greeting)
Output: Hello, my name is Charlie and I am 35 years old.
In this example, %s
is used for strings and %d
for integers. The values are passed as a tuple.
Which Method Should You Use?
If you're using Python 3.6 or later, f-strings are the best choice. They are concise, readable, and efficient. For older versions, format()
is a good alternative. %-formatting is generally discouraged for new code.
For more advanced string manipulation, check out our guide on Multiline Strings in Python.
Conclusion
String interpolation is a fundamental concept in Python. It allows you to create dynamic strings with ease. Whether you use f-strings, format()
, or %-formatting, the goal is to write clean and maintainable code.
For more tips on working with strings, explore our articles on checking if a string contains a float and trimming strings in Python.