Interpolate String in Python

Interpolate String in Python

  1. Use f-strings to Interpolate String in Python
  2. Use %-formatting to Interpolate String in Python
  3. Use Str.format() to Interpolate String in Python
  4. Use Template Strings to Interpolate String in Python

We will introduce the concept of string interpolation in Python and the methods for string interpolation, such as f-strings, %-formatting, str.format(), and Template strings.

When building an application that single or multiple users will use, we must use string interpolation several times to achieve a user-friendly interface. String interpolation is adding values of variables into placeholders in a string.

For example, if we want to welcome a user when logged in, we need to use a specific string like Hello {person name}, Welcome Back!.

The person’s name we need to place in this string is stored in a database. When we fetch it from the database, the name will be held in a variable, and we have to output this using string interpolation.

Use f-strings to Interpolate String in Python

With the update of Python 3.6, a new string interpolation method was introduced, known as literal string interpolation. The prefix used for this literal string interpolation is f.

This method is very powerful and easy to use. With the help of this method, we can easily access embedded Python expressions inside the strings.

Now, let’s go through an example in which we will store a user’s name in a variable and then use it to display a greeting message. With this, we will understand its syntax and usage.

# python
name = 'Husnain'
print(f'Hello {name}! Good Morning, Have a nice day.')

Output:

f-strings in Python Example Result

In the above example, the literal prefix f tells Python to restore the variable name value inside the curly brackets.

This string interpolation method is powerful because we can also embed arbitrary Python expressions.

So, let’s go through another example in which we will perform an arithmetic expression inside the string using the literal prefix f as shown below.

# python
a = 5
b = 3
print(f'5 multiply by 3 is {a * b}.')

Output:

f-strings in Python Example Using Arithmetic Expression Result

Use %-formatting to Interpolate String in Python

In Python, strings have a unique built-in operation that can easily be accessed with the % operator. We can easily do simple string interpolation using %.

Let’s understand its syntax and usage.

# python
print("%s %s" %('Hello', 'Husnain',))

Output:

%-formatting in Python Example Result

As you can see, we used the %s string format specifier, and we have two strings inside the parenthesis. We got both strings in the output.

The %s string format specifier will tell Python to substitute the value.

Now, instead of having strings in parenthesis, we add values from variables. We can quickly achieve this by changing the syntax slightly, as shown in the example below.

# python
name = 'Husnain'
print('Hello %s! Good Morning! have a nice day.' %(name))

Output:

%-formatting in Python Example With Variables Result

Suppose we have multiple variables, and we may not have to output the variables in the same order as we have them in parenthesis. In that case, we can also call the variables using the variable’s name, as shown below.

# python
name = 'Husnain'
greet = 'Evening'
print('Hello %(name)s! Good %(greet)s! have a nice day.' %(greet, name))

Output:

%-formatting in Python with Variable Name Calling Example Result

Using the % operator in this way makes our format strings easier to maintain and update in the future. We do not have to worry about the order.

We can easily replace the variables, and it will work fine no matter how we have ordered it.

Use Str.format() to Interpolate String in Python

Str.format() is another method in Python that can be used for string interpolation. This method is almost the same as %-formatting in syntax and usage.

In Str.format() we use a format() function on a string object and curly brackets. We use variables in the format() function and these variable values are displayed in {}.

Let’s go through an example to understand the syntax of this method.

# python
name = 'Husnain'
print('Hello {}'.format(name))

Output:

str-formatting in Python Example Result

The above example is almost similar to the one we used in %-formatting.

Suppose we have multiple variables that we want to interpolate into a string. In that case, we can use variable names inside {} to specify which variable is used at a certain point of a string, as shown below.

# python
name = 'Husnain'
greet ='morning'
print('Hello {name}! Good {greet}.'.format(name=name,greet=greet))

Output:

str-formatting in Python Example With Multiple Variables Result

Use Template Strings to Interpolate String in Python

Template strings can also be used for string interpolation. These are more straightforward and less powerful methods for string interpolation.

We need to import the Template class’s string module to use this method below.

# python
from string import Template

Now, we can define variables and create a new template using the Template method, as shown below.

# python
name = 'Husnain'
greet = 'Morning'
newTemplate = Template('Hello $name! Good $greet.')

We can print this template, but we have to replace the values in the template using a substitute method.

# python
print(newTemplate.substitute(name = name, greet = greet))

Output:

Template Strings in Python Example Result

Summary

Here are some important points about the above methods we used.

  1. The f-strings method is the most powerful and easiest method that also increases the readability of the code.
  2. %-format method is an old method and not recommended to use because it decreases the readability of the code.
  3. In str.format() we need to pass the string object the format() function for string interpolation.
  4. In Template strings, we create templates by importing the Template class from the built-in string module.

In this tutorial, we discussed four different methods that can be used for string interpolation. We also learned the syntax and how to use all of these methods in our application without any problems.

Rana Hasnain Khan avatar Rana Hasnain Khan avatar

Rana is a computer science graduate passionate about helping people to build and diagnose scalable web application problems and problems developers face across the full-stack.

LinkedIn

Related Article - Python String

  • Remove Commas From String in Python
  • Check a String Is Empty in a Pythonic Way
  • Convert a String to Variable Name in Python
  • Remove Whitespace From a String in Python
  • Extract Numbers From a String in Python
  • Convert String to Datetime in Python