How to Interpolate Strings in Python?

Python Tutorials

Summary: In this tutorial, you will learn two different ways to interpolate strings in Python.

Interpolation is the process of evaluating strings that contain one or more placeholders for substitution with values.

In python, we can easily interpolate strings using string.Template.substitute() method or string placeholder. Let’s see an example of each.

Use string.Template.substitute() to interpolate Strings

import string

template = string.Template("My name is $name")
final_string = template.substitute(name="Adarsh")

print(final_string)

Output: My name is Adarsh

First, create a string using the syntax "$placeholder" with placeholder as the desired name of the placeholder for the string. Place additional characters before or after $placeholder, if any.

Then, call string.Template(template) with template as the string from the previous step to create a Template for string interpolation.

Finally, call string.Template.substitute(placeholder_name=value) with string.Template as the Template from the previous step, placeholder_name as the name of the placeholder variable, and value as its value to substitute into the string.

Use literal String Interpolation to Interpolate Strings

name = "Adarsh"
final_string = f"My name is {name}"

print(final_string)

Output: My name is Adarsh

Here, we first created a placeholder string for interpolation, then interpolated a string using the syntax f"{placeholder}" with placeholder as the name of the variable from the previous step.

In the string, additional characters can go anywhere before or after the braces.

There were the two ways using which you can easily interpolate string in Python programming language.

Leave a Reply

Your email address will not be published. Required fields are marked *