Python String Interpolation. Learn the basics of string... | by Iffat Malik Gore | Towards Data Science

String interpolation is a process of injecting value into a placeholder (a placeholder is nothing but a variable to which you can assign data/value later) in a string literal. It helps in dynamically formatting the output in a fancier way. Python supports multiple ways to format string literals. All string interpolation methods always return new values and do not manipulate the original string.
Apart from its normal calculation usage, % operator is overloaded in str class to perform string formatting, it interpolates various class types into the string literal. Below are some commonly used format-specifiers,
General format for using % is,
Here, % indicates a conversion type of string when using Python’s string formatting capabilities.
Output:-------Result of calculation is 4.38Hey! I'm Emma, 33 years old and I love Python ProgramingHey! I'm Emma and I'm 33 years old.
In the above example, we have used two %s and one %d format specifiers which are nothing but placeholders for a tuple (‘Emma’, 33, ‘Python’) values. % takes only one argument and hence tuple is used for multiple value substitution. Note that, the values of a tuple are passed in the order they are specified. Python will throw TypeError exception if the type of a value and the type of corresponding format specifier doesn’t match.
In the below code, %d is a format specifier for first value ‘Emma’ which is a string, and hence TypeError exception is raised.
print("\nHey! I'm %d, %d years old and I love %s Programing"%('Emma',33,'Python'))  --------------------------------------------------------------------TypeError                                 Traceback (most recent call last)<ipython-input-5-f2e9acc11cdb> in <module>      1 ----> 2 print("\nHey! I'm %d, %d years old and I love %s Programing"%('Emma',33,'Python'))  TypeError: %d format: a number is required, not str
Though %-formatting is available since the beginning in Python, it is clumsy when there are multiple substitutions in a single string.
Str.format( ) is used for positional formatting, this allows re-arranging the order of placeholders within string literals without changing the order they are listed in .format( ). { } is used as a placeholder and only value passed by method .format( ) will be replaced by { }, the rest of the string literals will be unchanged in the output.
Positional formatting can be achieved by using either index or keyword in placeholders. If none of them are specified, objects will be injected in the order they are mentioned in .format( ), by default.
Output:-------Hey! I'm Emma, 33 years old, and I love Python Programming.33 years old Emma loves Python programming.Emma loves Python programming and she is 33 years old.
Use either indexing/keywords or keep it black, you cannot hybrid them together as Python will throw ValueError exception. In the below code, two of the placeholders are kept blank and one has index ‘2’ reference and hence the exception is raised.
name="Emma"age=33lan="Python"print("{} years old {2} loves {} programming.".format(age,lan,name))--------------------------------------------------------------------ValueError                                Traceback (most recent call last)<ipython-input-15-b38087c9c415> in <module>      5 lan="Python"      6 ----> 7 print("{} years old {2} loves {} programming.".format(age,lan,name))      8 ValueError: cannot switch from automatic field numbering to manual field specification
.format( ) method is versatile and can be easily used with all data structures as well.
Output:-------Hey! My name is Emma, I'm 33 years old, currently living in UK and love Python programmingPerson info from List: Emma from UKPerson info from Tuple: Emma 33 UKPerson info Set: 33 Python Emma
As shown in the code above, values received from dictionary person_dict have key-values as placeholders in a string literal. ‘**’ (double asterisk) is used for unpacking dictionary values mapped to key-values.
For both list and tuple, indexing has been used in a placeholder.
f-string or formatted string literal provides a way of formatting strings using a minimal syntax. (It was introduced in Python 3.6). Code readability is high and hence it is generally preferred way of formatting string literals. ‘f’ or ‘F’ is used as a prefix and {} are used as placeholders. Unlike .format( ), f-string doesn’t allow empty braces {}. F-string expressions are evaluated at run time.
F-strings are faster than the two most commonly used string formatting mechanisms,%-formatting and .format( )
Output:-------Emma is 33 years old currently living in UK and loves Python programming.33 years old  Emma lives in UK and loves Python programming'Emma' is a python developer from UKDate in default format: 2020-06-04 17:01:31.407452 Date in custom format: 04/06/20
As shown in the above code, we just have to append ‘f’ at the beginning of the string and include variable names directly into placeholder { }. f-string formatting can be seamlessly used with class and its objects as well.
Output:-------Person Details: Emma is 33 years old Python developer.[Name: Emma, Age: 33, Programming_language: Python]
Here, we have defined two methods in Person class. Appended ‘f’ at the beginning and class/object reference variables are placed in { }.
Clean and precise!
Another way of string interpolation is facilitated by Template class of String module. It lets you make substitutions in a string using a mapping object. Here, a valid python identifier preceded by sign ‘$’ is used as a placeholder.
Basically, we can define a string literal using a Template class object and then map the value of placeholders through substitute( ) or safe_substitute( ) method.
‘$’ sign performs the actual substitution and the identifier is used to map the replacement keywords specified in method substitute( ) or safe_substitute( ).
substitute( ) — It raises an error if the value for the corresponding placeholder is not supplied.
safe_substitute( ) — It is more appropriate when there is a possibility of incomplete user-supplied data. (When data is missing, it leaves the placeholder unchanged.)
Output:-------Emma is 33 years old and loves Python programming!$age years old Emma loves Python programming$age years old Harry loves Java programming
In the above example, we have created object person_info of Template class which holds the string literal. Then actual values are injected using substitute( ) method, it maps the values to placeholder names.
substitute( ) raises an error if the value for the corresponding placeholder is not supplied. Here, no value for $years is supplied in substitute( ) and hence it raises KeyError exception.
person_info=Template('\n$name is $years years old and loves $lan programming!')   print(person_info.substitute(name='Emma',lan='Python'))--------------------------------------------------------------------KeyError                                  Traceback (most recent call last)<ipython-input-7-2b10997fef23> in <module>      4 #creating object of Template class      5 person_info=Template('\n$name is $years years old and loves $lan programming!')----> 6 print(person_info.substitute(name='Emma',lan='Python'))  #substitute()      7       8 ~\Anaconda3\lib\string.py in substitute(*args, **kws)    130             raise ValueError('Unrecognized named group in pattern',    131                              self.pattern)--> 132         return self.pattern.sub(convert, self.template)    133     134     def safe_substitute(*args, **kws):~\Anaconda3\lib\string.py in convert(mo)    123             named = mo.group('named') or mo.group('braced')    124             if named is not None:--> 125                 return str(mapping[named])    126             if mo.group('escaped') is not None:    127                 return self.delimiterKeyError: 'years'
In the same example, we have also used safe_substitute( ) where we have not assigned any value for the place holder $age and hence it remains the same in the output without raising any exception.
$age years old Emma loves Python programming$age years old Harry loves Java programming
This method is considered for complex customized string manipulations; however, the biggest limitation of str.Template class is, it only takes string arguments.
I personally use f-string most of the time as it is concise, very convenient to write, and at the same time, code readability is high. Some of the great resources for the topic are,
PEP 498 — Literal String Interpolation
Formatted String Literals
The code used in this article can be accessed from my GitHub Repository.