String interpolation is a very common operation in Python like any other programming language. It is used to format strings in the desired manner. Programmers normally specify string literals in their code which often contain certain placeholders or variables which need to be replaced with their corresponding values. String interpolation is the process in which this replacement or substitution takes place. String interpolation in Python can be done in a number of ways. However, in this blog post, I am going to discuss only the two most commonly used methods: str.format() and f-strings.
String Interpolation in Python Method 1: str.format()
In this method, you define a format string which contains special "replacement fields" surrounded by curly brackets { }. Any text which is not contained in braces is treated as literal text and is passed unchanged to the output.
Each of the replacement fields can either be a number or a keyword. If it's a number, it refers to a positional argument, and if it’s a keyword, it refers to a named keyword argument.
Examples of Format Strings
Usage
Let's assume we have the following piece of Python code:
Now, we can make use of different format strings to produce different outputs as shown below:
I hope the usage of str.format() is clear through the above examples. If you need to include a brace character in the literal text, it can be escaped by doubling: {{ and }}. It is important to note that str.format() supports several other advanced functionalities. Replacement fields can contain more than just an argument name. You can have a conversion field and a format specification field as well. You can read more about them here: https://docs.python.org/3/library/string.html#format-string-syntax.
String Interpolation in Python Method 2: f-strings
Formatted strings or f-strings are string literals that are prefixed with 'f' or 'F'. f-strings can contain replacement fields. These replacement fields are expressions delimited by curly brackets { }. An f-string in Python is not a constant value. It is an expression which is evaluated at run time.
Usage
Let's assume we have the following piece of Python code again as shown above:
We can make use of f-strings to produce different outputs as shown below:
f-strings were introduced in Python 3.6 and are the recommended way to perform string interpolation in Python.