String Interpolation in Python : Seamless String Formatting

Siddhant Tiwari
4 min readFeb 14, 2023

--

How to Infuse Variables into your String

String formatting or interpolation is a powerful feature in Python that helps to construct strings in a more readable and efficient way. Imagine you are working on a web application where you need to display a personalized message to users upon login. The message includes the user’s name and age, which are fetched from a database.

Without string formatting, the only way to create the message is by concatenating strings as follows:

name = "John"
age = 23
message = "Hi " + name + "! I know you are " + str(age) + " years old."

This approach can quickly become unruly and difficult to read, especially when dealing with more than a handful of variables.

Python’s string interpolation offers a better way to format strings. Using string interpolation, you can substitute variables directly into a string using placeholders. While there are multiple ways to do that and we are going to discuss some of the best practices with their use cases:

1. Interpolation Using f-Strings

f-strings in Python are string literals that allow expressions to be embedded inside the string, evaluated at runtime. They improve readability, conciseness, efficiency, and flexibility in string formatting. They can be used to format a variety of data types, and with various formatting options.

Overall, f-strings are a useful tool in Python 3.6 or later for creating efficient and readable code. As you can see the below code if much more readable and easy to understand now:

name = "John"
age = 23
message = f"Hi {name}! I know you are {age} years old."

2. % Operator Formatting

The % operator is an older method of string formatting in Python that allows you to insert variables into a string. To format a string using the % operator, you need to specify a format string and a tuple of values to be inserted into the string.

The % operator can be helpful in situations where you need to format strings using legacy code or when working with Python versions that do not support f-strings. Additionally, the % operator allows you to apply more complex formatting to strings, such as padding, alignment, and precision.

name = "John"
age = 23
message = "Hi %s! I know you are %d years old." % (name, age)

3. Interpolation Using { } and .format()

You can use curly braces with the .format() method to insert variables into a string. Place the variables inside the curly braces {} and use .format() to substitute them into the string. Below code example shows how to use { } with .format().

name = "John"
age = 25
print("My name is {} and I am {} years old".format(name, age))

4. Interpolation Using format_map() and Dictionary

Suppose you have loaded a JSON object into a Python dictionary and want to substitute the values of the dictionary’s attributes into your string. Python has you covered with the format_map() method, which maps dictionary variables to placeholders in the string. To use this method, simply create a string with placeholder curly braces, and call the format_map() method on that string, passing in the dictionary as an argument. The method will automatically replace each placeholder with the corresponding dictionary value, resulting in a fully interpolated string. Here's an example:

person = {"name": "John", "age": 25}
print("My name is {name} and I am {age} years old".format_map(person))

5. Using Python’s String Template

To format strings in Python, one technique involves creating a template string with placeholders and then using the “substitute()” method to replace the placeholders with the desired values. This method can be helpful when you have a fixed template that you want to reuse with different values, as it allows for a clear separation between the template and the values being substituted.

from string import Template

person = {"name": "John", "age": 25}
template = Template("My name is $name and I am $age years old")
print(template.substitute(person))

In conclusion, Python provides several techniques for string interpolation and formatting, each with its own advantages and use cases. When working with string interpolation, it’s important to consider the complexity of your data, the desired output format, and the readability and maintainability of your code. F-strings have quickly become a popular choice for their simplicity, readability, and performance. However, depending on the requirements of your project, other methods may be more appropriate. Overall, by choosing the right string interpolation technique for your project, you can improve the efficiency and readability of your code, making it easier to maintain and build upon in the future.

Cheers 🍻

--

--

Siddhant Tiwari

Writing to Simplify Technology, Software Engineer, Security Analyst