String Interpolation in Python | 3 Best Methods To Follow

Finding it challenging to implement string interpolation in Python? If yes, then have a look at this guide to understand all about string interpolation in Python.

When writing code for programs, we encounter many situations when we may have to display customized text based on the logic behind the program. More often then not, most the message remains the same except for some parts, which we need to change dynamically (it means while the code is being run) on the basis of some variable or other program logic. 

In such cases, string interpolation saves us a lot of efforts. There are many ways to implement String interpolation in python. But before discussing them in detail, let us first talk about what is a string in python.

What is a String ?

A string in a programming language is basically a continuous collection of characters. Now what are characters ? Characters can be understood as symbols on the keyboard. Alphabets, numbers and special characters ( ., @, # etc.) are all considered characters and can be a part of a string.

In python, there is no separate data type for characters, so every character data or string data is stored as string. These are also immutable which means once created, their value cannot be modified. 

There are many string modification methods like join(), concatenate() etc. but they don’t change the actual string, but they create a copy of the actual string and modify it according to the functions.

Example:

str = 'this is a string'

print(str)

Output:

this is a string

What is String Interpolation ?

String Interpolation basically means to placing a placeholder inside a string to change its value dynamically, while keeping the rest of the string same.

What this means is that we can tell python interpreter that there is some part of the string that we want to change dynamically (at run-time) and the interpreter will take some variable or other form of input for the designated place, every time the program is executed.

We are going to discuss 4 ways to do string interpolation in python. Let’s dive into it.

Using % formatting

In this method, a ‘%’ sign is placed as a placeholder in the string to tell the interpreter that we want to insert some dynamic value here.

At the end of the string, we place another ’%’ sign followed by an ‘s’ and write the values for the dynamic strings (they can be in the form of variables) inside parentheses ‘()’ in the order of the placeholders placed.

Example:

name = 'Rohan'

order = 'Burger'

str = 'Hello %s, Your order is %s'%(name, order)

print(str)

Output:

Hello Rohan, Your order is Burger

The ‘%s’ is not the only % symbol. The s in the ‘%s’ symbol tells the interpreter that the placeholder must be substituted with a string value. For other data types, there are various other symbols

%s  : when the placeholders is to be substituted by a string

%d : when the placeholders is to be substituted by an integer value

%c : when the placeholders is to be substituted by a special character

%o : when the placeholders is to be substituted by an octal value

%x : when the placeholders is to be substituted by a hexadecimal value

%r : when the placeholders is to be substituted by the raw value of a variable

Using Template

String Interpolation can also be done using the template class from the string module. A module contains several classes. These classes contain variables and their related functions to provide additional functionality.

If we oversimplify things, the class can be understood similar to a data type, but created by the user according to their needs, containing several variables and functions that increase functionality of the program.

So how is template class useful ? The template class can be used for string interpolation by placing ‘$’ signs followed by an alias (basically a variable name to identify the placeholder) as placeholders. We can then use the substitute method in the template class to replace the placeholders with the required text.

Example:

from string import Template  # Syntax to import a class from a module

str = Template('Hello $name, Your order is $order')

name = 'Rohan'

order = 'Burger'

print(str.substitute(name = name, order = order))

Output:

Hello Rohan, Your order is Burger

Using str.format()

This method is similar to the template method. But instead of ‘$’ signs, we use curly-braces ‘{}’ as the placeholders. The format functions can then be used to replace those placeholders with the required data by passing the placeholder values as parameters in the order of the placeholders.

Example:

name = 'Rohan'

order = 'Burger'

str = 'Hello {}, Your order is {}'.format(name, order)

print(str)

Output:

Hello Rohan, Your order is Burger

Using f strings (most used)

This method is one of the most used ways to perform string interpolation. But why the name ‘f strings’. This is because we put an ‘f’ in the starting of the string that we want to interpolate. Then we can use curly braces to directly change the values inside the string. Yes that’s it ! The below example will clarify the usage of f strings.

Example:

name = 'Rohan'

order = 'Burger'

str = f'Hello {name}, Your order is {order}'

print(str)

Output:

Hello Rohan, Your order is Burger

Conclusion

String Interpolation is a very frequently needed task in programming. There are many ways to perform string interpolation in python. Some methods may look inferior to others but they all contribute to understanding the nature of programming and how the methods work.

Therefore, it becomes necessary to know about all the different methods to perform a task and choose the most appropriate one for the specific program.

The f strings method is the most suitable(in most cases) method for string interpolation as it retains the readability of the code much better compared to the other methods.

Leave a Comment

Exit mobile version