String interpolation is a technique to add values of variables into placeholders in a particular string. The changes carried out by these methods are dynamically implemented and make it easy for the developers to design a program.
The literal meaning of the word interpolation is to put in between or among others. In this article, we will understand four string interpolation methods in Python with syntax and supporting examples so that you can choose the one that suits you best.
Methods of String Interpolation in Python
Python supports multiple ways to format strings but we will be only focusing on those that are efficient and mainly used by programmers.
String Interpolation in Python can be done using the following ways:
- %- formatting
- str.format()
- f-string
- String Template Class
Also Read: Check if a Python String Contains a Substring
%- formatting
This is the most basic and straightforward way of formatting a string. The modulo (%) operator can insert multiple variables in a string.
- %s – string insertion
- %c – character insertion
- %d – integer value insertion
- %f – floating point values insertion
- Refer to more here
The above-mentioned are some format specifiers, that replace themselves with value mentions at the end of the string. Refer to the following example.
Example 1:
name = "Tanvi"
print("%s is learning Python" %name)
print("%s refers %s website"%(name,'AskPython'))
Output:
Tanvi is learning Python
Tanvi refers AskPython website
Example 2:
x = 24
print("We have %d hours a day."%x)
y = 8.5
print("We spend around %f hours sleeping."%y)
z = "a"
print("The first alphabet is %c."%z)
Output:
We have 24 hours a day.
We spend around 8.500000 hours sleeping.
The first alphabet is a.
str.format()
It is a built-in function that makes formatting a string in Python even more convenient. The position of variables to be added is taken by curly braces – {}, and the value of the variable is passed after the string ends by calling the str.format() function. This way of Python string formatting is considered more efficient is it can handle variables of all kinds in one uniform way.
Syntax:
{}.format(value/s)
Parameters:
The parameter passed can be multiple too. The value can be an integer, floating point value, character, string, or any other variable.
Example 1: Single Variable
#Method 1:
string1 = "AskyPython helps you to learn {}"
print(string1.format("Python"))
#Method 2:
print("{} is interpreted language".format("Python"))
print("Python was invented in {}".format(1991))
Output:
AskyPython helps you to learn Python
Python is interpreted language
Python was invented in 1991
Example 2: Multiple Variable
print("Every month, over {} new computer {} are released.".format(5000, "Viruses"))
x1 = 1979
print("The {} hard drive was made in {}.".format("first",x1))
print("\n")
#will return error
print("{} is {}, {} {} programing language".format("Python","high-level", "interpreted"))
NOTE: The number of placeholders ( {} ) should be equal to the number of variable values passed in .format(). Or else, the tuple index will be out of range and thus IndexError will occur.
Output:
Every month, over 5000 new computer Viruses are released.
The first hard drive was made in 1979.
Traceback (most recent call last):
File "", line 8, in
IndexError: Replacement index 3 out of range for positional args tuple
f-string
Also known as formatted string literals. This is a way of literal string interpolation that is more readable, convenient, and efficient but it is available in Python3.6 and later versions only. F-strings are faster than both the %-formatting method and str.format() method. The string is initialized with “f” as a prefix and mentions the variable names in {} at their correct position.
Example:
x1 = "Python"
print(f"Ask{x1} has articles on the {x1} language")
x2 = 1991
print(f"{x1} was invented in {x2}")
Output:
AskPython has articles on the Python language
Python was invented in 1991
String Template Class
This method is a bit lengthy and provides less convenience when compared with other methods of string formatting in Python. Firstly, the Template class is needed to import from the string module in Python. Template strings support $-based substitutions. $identifier names a substitution placeholder matching a mapping key of “identifier”. By default, “identifier” is restricted to any case-insensitive ASCII alphanumeric string (including underscores).
Example:
name = "Tanvi"
str1 = Template("My name is $name")
print(str1.substitute(name = name))
Output:
My name is Tanvi
Frequently Asked Questions (FAQs)
What is Python string interpolation?
Python string interpolation is a method of substitution placeholders in a string with values. Placeholders are basically variables to which we can assign values.
What are the four interpolation methods?
The four methods of string interpolation are %- formatting, str.format(), f-string and String Template Class where the most recommended method is f-string introduced in Python 3.6.
Which method is best for interpolation?
The best method for string interpolation is to use f-string which is a relatively new string formatting mechanism that lets us embed the value of Python expressions inside string literals which also helps in increasing overall readability.
What are the benefits of string interpolation?
There are many benefits of using string interpolation such as a better interface, creating templates, displaying data, etc. But one of the key benefits is to create dynamic content, you can insert different data to generate customised results.
What is %s and %d in Python?
In Python, both %s and %d are placeholders where %s is used for inserting string values into a string and %d is used for inserting integer values.
Is string interpolation data binding?
Data binding means combining source data with target data. String interpolation is a certain case of data binding, where the source data is a variable and the target data is a string.
What is the difference between string interpolation and concatenation?
String concatenations means combining two or more strings together, one after the other. Whereas string interpolation is a process of inserting values, variables, or expressions into a string.
Conclusion
In this article, we understood multiple ways to perform string interpolation in Python. The most commonly recommended methods are either f-string or str.format(), as they have fewer chances to return any kind of errors.
Read More: Python Keywords – Simply Explained!
References
- https://peps.python.org/pep-0498/#id13
- https://docs.python.org/3/library/string.html#formatstrings
- https://docs.python.org/3/library/string.html#template-strings