Many times we come across various situations in which we want the output string to change dynamically. For example, say we wanted to greet the user Hello, every time a new user enters the system. We cannot hardcode the output string to be “Hello User” and then expect it to replace the user’s name every time a new user comes in.
So how do we make it possible? We make it possible with String Interpolation in Python. A string that uses string interpolation would look like, “Hello ” where is the placeholder that can be replaced with whatever value we want to display there.
We will see the 4 different ways to achieve this in python and with examples also understand how each way works.
What is String Interpolation in Python?
In Python, String Interpolation means placing a placeholder inside a string that can be dynamically changed based on some variable’s value. It is used often when the elements inside a string are not known or could be changing from time to time.
String Interpolation refers to inserting values into a string, these values are often dynamic and are generated during run time. There are various methods of implementing string interpolation that we shall discuss below:
01) % formatting
The % formatting in python is perhaps the most naive way of performing string interpolation in python. We simply place, the % sign wherever we expect to put a placeholder and then provide the values of the placeholder after the string, this is depicted in the example below:
user = "Abrar" age = "20" print("Hello %s. Your age is %s "%(user,age))
Output:
Hello Abrar. Your age is 20
There are some special types of % signs that we can use when we want to let the compiler know what intended value we want to provide in the placeholder. For example, if we want the placeholder to only be replaced by integer values we use the symbol %d.
Similarly, various other symbols can be used for various reasons, some of which are the following:
- %s: when we want the placeholder value to be a string
- %f: when we want the placeholder value to be a floating point decimal like 2.415
- %r: when we want to replace the placeholder with the raw data of a variable
- %x: when the value replacing the placeholder has to be a hexadecimal value
- %o: when the value replacing the placeholder has to be an octal value
- %c: when we want to replace the placeholder with special characters
02) str.format
The str.format() is a function that allows us to perform string interpolation. Using this method, instead of providing a % sign as a placeholder, we define the placeholder using curly braces { }. The values that we want to replace in the placeholder are passed as arguments to the format function.
An example depicting this is provided below:
user = "Abrar" age = "20" print("Hello {}. Your age is {} ".format(user,age))
Output:
Hello Abrar. Your age is 20
We can also provide names to our placeholders for easier readability in our programs. Obviously with too many interpolations to make, we would lose track of which curly brace is getting replaced with what values.
Therefore to name the placeholders, we just provide a name inside the curly brace that we then use while passing the values of the placeholders in the format function.
user = "Abrar" age = "20" print("Hello {name}. Your age is {age} ".format(name=user,age=age))
Output:
Hello Abrar. Your age is 20
03) Template
A template is a class inside the string module. A class is a bunch of variables and their associated functions that can be accessed by a single name and a module is a bunch of these classes. How do we do string interpolation using the template class?
The template class allows us to create templates with placeholders in them that we can later use to substitute the placeholder values. You can create a template by using the $ sign as a placeholder and then use the substitute function inside the template class to replace it with placeholder values.
You can have a look at the example below to understand this concept in a better fashion.
from string import Template welcome = Template("Hello $name. Your age is $age") user = "Abrar" age = "20" print(welcome.substitute(name=user,age=age))
Output:
Hello Abrar. Your age is 20
04) f strings
f strings are perhaps the easiest way of performing string interpolation in python. f strings were introduced after python 3.6 and life has become easier since then. Why do we call it f string? Well, any string on which you want to perform string interpolation using this method has to begin with the letter f before the quotes.
So if you were to use an f string for wishing hello to every new user, you would write f” Hello ”. But what makes f strings so easy to use? Unlike the other three methods that we saw, you do not have to define the placeholder and their values separately.
You read it right! Using f strings you can directly interpolate values into the string by providing the values in curly brace inside the string. Have a look at the example below and it will become crystal clear to you.
user = "Abrar" age = "20" print(f"Hello {user}. Your age is {age}")
Output:
Hello Abrar. Your age is 20
Conclusion
String interpolation in Python is a frequent task that requires us to dynamically change the value of a string. It can be achieved in four manners based on the programmers' needs.
Strings can be interpolated using the % sign, the format function, the Template class, or using f strings. The % sign is not preferred as it decreases the readability of the program whereas the f strings method is the most preferred as it is easier and increases code readability.