A simple introduction to Python String Interpolation

Photo by Markus Spiske on Unsplash

Process of evaluating a string literal containing one or more placeholders that are replaced with their corresponding value is known as string interpolation.

In python we have a few methods to handle this. Through this article, I will try to introduce them to you and try to guide you to the best method to use.

first_name = 'John'
last_name = 'Doe'
age = 28

Let us start with these 3 variables that carry 2 string values and an integer.

we want to create an output ‘Welcome Mr. John Doe(28)’

1. string formatting (old) (% operator)

%-format method is a very old method for interpolation and is not recommended to use as it decreases the code readability. Strings in Python have a unique built-in operation that can be accessed with the % operator. if you learned coding from C++ like me, You will instantly recognise this method.

print("Welcome Mr. %s %s(%s)" %(first_name, last_name, age))

2. “new” String Formatting (str.format)

With the python 3 format() was introduced which got rid of the % operator syntax. this was also ported to python 2.7.

In str.format() method we pass the string object to the format() function for string interpolation. we can use .format to do some simple positional formatting or you can use variable substitutions and change the order.

print("Welcome Mr.{} {}({})".format(first_name, last_name, age));

or

print("Welcome Mr.{first_name} {last_name}({age})".format(last_name=last_name, age=age, first_name=first_name));

3. f-strings

The new string formatting mechanism introduced by python 3.6 or PEP498 is known as Literal String Interpolation or more commonly as F-strings (because of the leading f character preceding the string literal). The idea behind f-strings is to make string interpolation simpler.

print(f'Welcome Mr. {first_name} {last_name}({age})')

4. String Template Class

In the String module, Template Class allows us to create simplified syntax for output specification. The format uses placeholder names formed by $ with valid Python identifiers (alphanumeric characters and underscores). Surrounding the placeholder with braces allows it to be followed by more alphanumeric letters with no intervening spaces

from string import Template
new = Template('Welcome Mr. $first_name $last_name($age)')
print(new.substitute(last_name=last_name, age=age, first_name=first_name))

Literal String Interpolation method or the F-strings is powerful interpolation method which is easy to use and increase the code readability.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store