Hello readers, in this article we will understand string interpolation in python. The literal meaning of the word interpolation is to put in between or among others.
Thus, in simple words, we can say that string interpolation is a method 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.
String Interpolation can be using the following ways
- %- formatting
- str.format()
- f-string
- String Template Class
Also read: 4 Easy Methods to Append Multiple Strings in Python
%- formatting
This is the most basic and most 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
- etc Refer 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.
name = "Tanvi"
print("%s is learning Python" %name)
print("%s refers %s website"%(name,'AskPython'))
OUTPUT:
Tanvi is learning Python
Tanvi refers AskPython website
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 formatting is considered more efficient is it can handle variables of all kinds in one uniform way.
The syntax: {}.format(value/s)
parameter: The parameter passed can be multiple too. Value can be an integer, floating point value, character, string, or any other variable.
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
Multiple Variable
NOTE: The number of placeholders ( {} ) should be equal to number of variable values passed in .format(). Or else, the tuple index will out of range and thus
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"))
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 way of formatting 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
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. Firstly, the
name = "Tanvi"
str1 = Template("My name is $name")
print (str1.substitute(name = name))
OUTPUT:
My name is Tanvi
Conclusion
In this article, we understood how to format strings in python in four different ways. The most commonly recommended methods are either string or str.format(), as they have lesser chances to return any kind of errors.
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