String interpolation is used to substitute values of variables into placeholders present in the string. For example, if we have a template for greeting a person like “Hello {Name of person}, good to see you!”, by using python string interpolation this placeholder for the name of the person can be replaced with any person’s actual name.
By using string interpolation in python you can dynamically replace the placeholders with the desired user-defined input without creating a new string every time.
In this article, you will get a deep insight into python string interpolation in detail and multiple ways to format text strings along with examples.
f-strings
A new string interpolation method is introduced by PEP 498 known as literal string interpolation, also known as f-strings because it has a prefix ‘f’ character preceding the string literal. It is a new powerful and easy way of formatting strings.
You can create an f-string by adding the prefix ‘f’ to the string and then you will have access to the embedded python expressions inside string constants more conveniently.
Program:
# Python program to demonstrate the working of f-strings
n1 = 'Hey'
n2 = 'Niharika'
# f tells Python to restore the value of two string
# variable name and program inside placeholders
print(f"{n1}! This is {n2}")
Output
Hey! This is Niharika
f-strings can also be used to evaluate the value of some arithmetic operations by performing the inline arithmetic.
Program:
a = 4
b = 2
c = 8
print(f"({a} * {b})-{c} = {(4 * 2)-8}")
Output
(4 * 2)-8 = 0
%-formatting
%-formatting is a unique built-in feature provided by a python that can be accessed with the % operator. It makes string interpolation very easy and is similar to printf style function in C. This formatting is very useful when we have a lot of variables that we want to substitute in string.
Program:
# Python program to demonstrate the working of string interpolation
m1 = 'Hi'
m2 = 'Niharika'
# implementation for single substitution
print("Good to see you % s" % m2)
# implementation for single and multiple substitutions()
print("% s ! This is % s." % (m1, m2))
Output
Good to see you Niharika
Hi! This is Niharika.
We can also pass a mapping to the % operator to refer to variable substitutions by name in our format string.
Program:
name_1 = 'people'
name_2 = 'Article on python string interpolation'
print('Hello %(name_1)s! This is %(name_2)s.' %(name_1,name_2) )
Output
Hello people! This is Article on python string interpolation.
Str.format()
Str.format() is used to put desired words in one or more replacement fields known as placeholders denoted by a pair of curly braces{} into the string. The value you desire to replace with the placeholders and concatenate with the string is passed as parameters into the format function.
Program:
# Python program to demonstrate the working of string interpolation
n1 = 'Hi'
n2 = 'Niharika'
# implementation for single substitution
print('{}, {}'.format(n1, n2))
Output
Hi, Niharika
You can use the variable name inside the curly braces {}, this will allow you to use the parameters of format functions in any order you want.
You can rearrange the order of display without changing the arguments passed to the format function.
Program:
m1 = "Hi"
m2 = "Niharika"
# for single or multiple substitutions
# suppose b1 and b2 are formal parameters
# and m1 and m2 are actual parameters
print("{b1}! This is {b2}.".format(b1=m1, b2=m2))
# we can also change the order of the
# variables in the string without changing
# the parameters of format function
print("{b2}! This is {b1}.".format(b1=m1, b2=m2))
Output
Hi! This is Niharika.
Niharika! This is Hi.
Template Strings
Template strings are less powerful though a very simple method for string interpolation. It creates simplified syntax for output specification.
From the string module, we need to import the Template class to use this function. If you want to add a single $ sign, we have to use $$.
Program:
# Python program to demonstrate the working of string interpolation
# importing the Template class from the string module
from string import Template
m1 = 'Hi'
m2 = 'Niharika'
# made a template which we used to pass two variables so
# m3 and m4 formal and m1 and m2 actual
n = Template('$m3 ! This is $m4.')
# pass the parameters to be substituted into the template string.
print(n.substitute(m3=m1, m4=m2))
Output
Hi! This is Niharika.
Key Points to Remember:
- The %-format method is a very old method for string interpolation but as it decreases the code readability, it is not recommended.
- You have to pass the string object to the format() function in the str.format() method for string interpolation.
- In the template method, we have to import the template class from the built-in string module.
- The most powerful and easy method for string interpolation is Literal String Interpolation. It is easy to use and increases the readability of the code.
Frequently Asked Questions
Q.1. Does Python have string interpolation?
Answer: Python supports multiple ways to format text strings. Some of them are listed below:
- f-strings: A new string interpolation method is introduced by PEP 498 known as literal string interpolation, also known as f-strings because it has a prefix ‘f’ character preceding the string literal. It is a new powerful and easy way of formatting strings.
- %-formatting is a unique built-in feature provided by a python that can be accessed with the % operator. It makes string interpolation very easy and is similar to printf style function in C. This formatting is very useful when we have a lot of variables that we want to substitute in string.
- format() is used to put desired words in one or more replacement fields known as placeholders denoted by a pair of curly braces{} into the string. The value you desire to replace with the placeholders and concatenate with the string is passed as parameters into the format function.
- Template strings are less powerful though a very simple method for string interpolation. It allows you to create simplified syntax for output specification. From the string module, we need to import the Template class to use this function. The format uses placeholder names formed by $ sign. If you want to add a single $ sign, we have to use $$.
Q.2. What is string interpolation in Python?
Answer: String interpolation is used to substitute values of variables into placeholders present in the string. For example, if we have a template for greeting a person like “Hello {Name of person}, good to see you!”, by using python string interpolation this placeholder for the name of the person can be replaced with any person’s actual name.
Some specific formattings supported by python for string interpolation are f-strings, %-formatting, str.format() and template string.
Q.3. What is %s and %D in Python?
Answer: The %s and %d are format specifiers used to format strings and numbers respectively. The %s operator allows you to add a value to a python string and can be used to concatenate multiple strings.
Example:
name = “Meera”
print (“Hey, my name is %s” % name)
Output:
Hey, my name is Meera
The %d operator allows you to add numbers within the strings. It automatically converts floating-point numbers to decimal values.
Example:
value = 32
print(“Age of Meera is %d” % value)
Output
Age of Meera is 32
Q.4. Can I use string interpolation?
Answer: Yes, you can use string interpolation if you want to substitute values of variables into placeholders present in the string. Some specific formattings supported by python for string interpolation are f-strings, %-formatting, str.format() and template string. You can use any of these for string formatting.
Leave a Reply