How Does Python String Interpolation Work – With Examples
Strings are a common element in most programming languages. They can generally be thought of as a variable type consisting of plain, human-readable, text. But while most languages implement strings of some sort, Python has an innovative take on the idea. You can easily perform a wide range of operations on Python strings which would take a considerable amount of code in other programming languages. And one of the more important examples of this can be found in something known as string interpolation. You’ll soon see what makes Python’s string interpolation so useful, and examples of how you can leverage that power in your own code.
The Basic Structure of Python Strings and Interpolation
A Python string, on a technical level, is an array of Unicode formatted bytes. And this is in part why Python is so lenient with string manipulation. It’s easy to use strings in Python because the language as a whole makes it easy to work with collections – including arrays. You can easily swap data out from within a list or other collection. And, likewise, you can swap out segments of a string. This process is known as interpolation. Take a look at this example to see just how easy interpolation is in Python.
print(“Hello %s via interpolation” % “world”)
In this example, we enclose all of the program logic within a print statement. You can see that the example begins with fairly normal syntax for print. We call print, use quotation marks to begin a string, and start writing the intended output. The first unusual element is the %s. The % is known as a modulo in Python. And the s signifies that we’re working with a string. After some more text, we close out the string and use another modulo to pass a new string back to the original. In this case, it’s the “world” string.
When you run this code it will return “Hello world via interpolation”. The modulo was used to implement string interpolation. Again, this typically means using a placeholder value when first creating strings. These placeholders can then be easily swapped out with replacement text. We can even expand on this to insert multiple strings. As seen below, this can be accomplished with just a few small changes to the previous example.
print(“Hello %s via %s” % (“world”,”interpolation”))
The string replacement essentially fills in the placeholders as if it were moving through a checklist. The first %s matches up to the first string, the second %s to the second, and so on.
Different Types of String Interpolation
Modulo operators are one of the most common forms of interpolation for string formatting. However, this is far from the only way to go about the process. In addition to modulo, Python also provides template string, literal string, and a built-in string format method. The following example shows how we can use each of these techniques to print “Hello world via interpolation”. If you run this script you’ll see the name of every string interpolation technique in use and the hello world that results from it.
from string import Template
ourArea = “world”
ourTool =”interpolation”
print(“Using modulo:”)
print(“Hello %s via %s” % (ourArea,ourTool))
print(“Using templates:”)
ourTemplate = Template(“Hello $area via $tool”)
print(ourTemplate.substitute(area=ourArea,tool=ourTool))
print(“Using literal string:”)
print(f”Hello {ourArea} via {ourTool}”)
print(“Using format:”)
print(“Hello {}”.format(ourArea)+” via {}”.format(ourTool))
print(“Using format with multiple variable passes:”)
print(“Hello {ourArea2} via {ourTool2}”.format(ourTool2=ourTool, ourArea2=ourArea))
We begin by importing string’s Template class. As the name suggests, we’ll need it when we’re working with templates. Next, we define two new strings – ourArea and ourTool. We’ll be using these two variables consistently through every form of string interpolation.
The actual interpolation starts with a modified version of the earlier modulo example. There are two important differences from the original code. The first point to take note of is that we’re using string variables rather than directly passing strings of text. This might seem like a minor difference. But keep in mind that this highlights that interpolation is a normal part of Python. We don’t need to work through any data conversions or the like when passing text for substitution within a string. We just use standard Python variables.
The second important point is that we’re now using two strings for the interpolation rather than one. This requires us to make a minor change to the code’s syntax. We now enclose the strings in parentheses, with each separated by a comma.
We move on to templates in the next code block. This is the only commonly used form of interpolation which requires us to import an extra class. All of the other examples will still work without the initial import found on line 1. But with that in mind, templates are a powerful and extremely useful part of Python. However, it does have broader use than most of the other options. Python templates can be used for interpolation. But that’s really only scratching the surface of their potential. You’ll also note that in addition to requiring us to import the template class, this code block is the only one that uses two rather than one line for the “hello world” construction.
The extra work is often worth it though. We’re not just performing interpolation with the template. We’re creating a reusable form that can be easily fit into many different usage scenarios. For example, you might use a template for automated emails. And the Python script could fit an interpolated string into templates formatted for things like grade reviews, marketing, etc.
We begin using template-based interpolation by creating a template instance called ourTemplate. This is essentially just a standard string with one important exception. We define placeholders with the $ symbol. In the next line, we call substitute on the template while passing key/value pairs. The key is of course the elements we defined with the $. And the values in this example correspond to the ourArea and ourTool variables.
In the next code block, we use literal string interpolation. It’s important to keep in mind that Python’s string literal system is only implemented in Python 3.6 and above. However, the 3.6 release dates all the way back to 2016. As such, it’s generally safe to assume that any given user base will be using 3.6+.
We begin the literal string method by using the f literal prefix. This opens up a whole new world of functionality. But in this case, we’re limiting ourselves to simple string interpolation. We simply need to encase variable names in braces to swap them out with the associated string. A Python f string literal can encompass far more than this basic placeholder system though. You can easily use programming logic within the braces to create more dynamic string interpolation. Try swapping out the literal string example on line 14 with the following code.
print(f”Hello {ourArea} via {ourTool} and mor{1+2}”)
In this variation, we perform some basic arithmetic and pass the result into the string. The end result is the “and mor3” text. But take note that the 3 is automatically converted into the python string format. We can use this system to create endless variations on a newly formatted string literal.
The last example begins with a combination of the format function and string concatenation. The format method is a little cumbersome in comparison to the other options. But it also has some advantages. We use a curly bracket as the placeholder. Then we call format with the variable we want to pass into the brackets. Multiple substitutions are initially handled through string concatenation. As seen when we append “via” to the initial “Hello” string.
However, we can also use more advanced substitutions with format. Line 20 is similar to line 18 in that both are handling interpolation through format. But it has some important differences. The most readily apparent is that we begin by creating a single string that contains variable names in curly brackets. But in this example, we don’t break out of the string declaration to work with the format. We instead use new variable names as placeholders in the brackets. And we use format at the tail end of the string declaration. This lets us define the new placeholder variable names however we want. In this case, we simply pass on the contents of ourTool to ourTool2 and ourArea to ourArea2. This method is also notable for the fact that we aren’t limited to the placeholder’s order of declaration. We set ourArea2 before ourTool2 in the string declaration. But in format, we assign ourTool2 before ourArea2.
Real-World Usage Scenarios
You might be wondering which option is the best choice for interpolation. The simplest answer is that it often simply comes down to which option best fits your coding style. But if you’re simply looking for the most efficient way to handle interpolation then you’ll generally get the best result with string literal and f-string formatting.
The only caveat is that you need to ensure you’re only deploying the code to machines running Python 3.6 and above. This generally isn’t much of a concern. But you’ll run into compatibility issues if you’re writing for machines that are limited to Python’s 2.x branch. And some modern systems, like OSX and a few Linux distributions, keep Python 2.x as the default Python interpreter even though Python 3 comes preinstalled under the python3 alias. In those cases, you’ll need to make sure that users are correctly calling the Python 3 interpreter rather than their default Python 2.x.