What is String Interpolation?

  • How can one interpolate strings in Python?
  • Are there more than one ways to do the same?
  • If there is more than one way, what should be used when?
1 Like

In programming and not just Python, string interpolation is the process of substituting value of variables into one or more placeholders in a string. This process is completed without the use of + or string concatenation.

Yes, there are more than one way to interpolate strings in python.


%-Formatting (Old-way of formatting)
Strings in Python can be accessed with the % operator. As shown in the example below, %s format specifier is used to tell Python where to substitute the desirable string.

INPUT:

p1 = 'pencils'
p2 = 'pens'
print("I have 2 %s and 3 %s." % (p1, p2))  

OUTPUT:
I have 2 pencils and 3 pens.

It is to be noted that it can be used in any version of Python, but is not recommended type of string formatting for Python 2.6 and above. The following is the alternative.


str.format (New Way of Formatting)
A new way of formatting/interpolation was introduced in Python 2.6 and is now the recommended type of string formatting.
This new way/style got rid of the %-operator and makes the syntax for string formatting more regular. Now, .format() is called on a string for interpolation.

INPUT:

p1 = 'pencils'
p2 = 'pens'
print("I have 2 {0} and 3 {1}." .format(p1, p2))  #used in Python 2.6+
print("I have 2 {} and 3 {}." .format(p1, p2))  #used in Python 2.7+

OUTPUT:
I have 2 pencils and 3 pens.
I have 2 pencils and 3 pens.


f-Strings
In Python 3.6, a new type of string formatting/interpolation was introduced known as f-Strings. f-strings provide a way of inserting information into a normal string. This new way this prefixes the string constant with the letter f' ' or f" ".

INPUT:

p1 = 'pencils'
p2 = 'pens'
print(f'I have 2 {p1} and 3 {p2}.')

OUTPUT:
I have 2 pencils and 3 pens.


Template Strings
In this way, we need to import the Template class from Python’s built-in string module. Let us understand it with the help of an example.

INPUT:

from string import Template
p1 = 'pencils'
p2 = 'pens'
string = 'I have 2 $p1 and 3 $p2.'
print(Template(string).substitute(p1 = p1, p2 = p2))

OUTPUT:
I have 2 pencils and 3 pens.


When to use what?

  • Use Template Strings, when format strings are user-defined as user-defined/supplied data may be incomplete and the Template class provides a method such that Python will not throw a KeyError.
  • Use f-String or str.format, if using Python 3.6 or above.
  • Otherwise use, str.format.



Learn more about str.format() and f-Strings!!
Learn more about Template Strings!!

3 Likes