"
This article is part of in the series
Published: Friday 1st March 2024

Python String Interpolation: A Comprehensive Guide

There was a time when inserting values into strings dynamically was challenging in Python. This is why the string interpolation feature was introduced in Python 3.6. With it, you can insert variables into strings.

String interpolation makes string formatting straightforward, allows flexibility and output generation, and makes the code more readable. There are many string interpolation methods in Python, and in this brief guide, we will explore them with examples.

What is String Interpolation?

String interpolation involves the evaluation of string literals if any placeholders are present. The variable values then replace the placeholders. 

This feature helps reduce repetition in code and is typically used when the elements in a string aren't known or change from time to time.

Interpolating strings in Python involves the string temple and the value (or set of values) that belong inside the template. 

For the feature to work, the Python compiler must determine where to place the values inside the template. There are four ways to indicate the placement position to the compiler, each with some benefits and disadvantages. They are:

  • Using %: Placing a modulo character inside a string literal indicates to the compiler that it must replace the string there. The % character is followed by string format indicators and the names of the variables storing the values.
  • Calling .format() on the literal: Place a pair of curly brackets to indicate where to replace the string. You can use the function's arguments to indicate what values to replace the literals with.
  • Using f-strings: Put the letter f before any string literal to indicate the need for replacement. When using f-strings, literals can contain the variable to use for substitution and curly braces ({}) that delimit an expression. 
  • Using the Template class: You can store a string template in a variable using the Template class from the String module. You can then use the .substitute() method to indicate the substitution values. 

4 Methods of String Interpolation

Now, let's see these four methods of string interpolation in action.

#1 Using the Modulo Character

Using the % character is perhaps the most straightforward way to interpolate strings, at least in Python. You can put the % sign anywhere you want to put a placeholder. You can then supply the values to be substituted.

To use this string interpolation method, you must follow this syntax:

string % values

 

Here's some Python code that uses this method:

name = “Frank”

ID = “20403”

print(“Hi %s, your ID is %s” %(name,ID))

 

The output of this script is:

Hi Frank, your ID is 20403

 

Interestingly, there are different ways of using the module sign. You can use the sign with the different letters to tell the compiler what value to put in the placeholder. 

For instance, to replace placeholders with integer values only, you can use the %d symbol. Similarly, you can use other symbols to manipulate the placeholder values in various ways:

  • %c: Employed when replacing the placeholder with special characters.
  • %f: Employed for placeholder values representing floating point decimals, such as 2.415.
  • %o: Used when the value replacing the placeholder should be an octal value.
  • %r: Utilized to replace the placeholder with the raw data of a variable.
  • %s: Used when the placeholder value should be a string.
  • %x: Applied when the value replacing the placeholder must be hexadecimal.

#2 Using str.format() 

Using the .format() function provides more flexibility than the modulo method when performing string interpolation. Since the syntax of this method is more readable, you have greater control over the formatting of the string. 

You use curly brackets as placeholders instead of the modulo character in this method. The values you want to substitute in the placeholders must be passed to the format function as arguments.

The syntax of the str.format() function is:

string.format(values)

 

Here's an example of how this function is used:

name = “Frank”

ID = “20403”

print(“Hi {}, your ID is {}” .format(name,ID))

 

The output of this script is:

Hi Frank, your ID is 20403

 

There's more to using this function, though. Python allows you to name the placeholders when using the .format method. You can put the name of the placeholder inside the curly brackets. 

Giving names to placeholders is an excellent way to keep track of which placeholder needs which value. Let's see a short example:

name = “Frank”

ID = “20403”

print(“Hi {firstName}, your ID is {thisID}” .format(firstName=name,thisID=ID))

 

As you'd expect, the output is the same as when the placeholders aren't named:

Hi Frank, your ID is 20403

 

#3 Using the Template Class

With the template class, you can make templates that have placeholders. To create a template, use the $ symbol as a placeholder. You can then put a substitute function inside the class to replace the placeholder with the values.

This method is best explained with an example:

from string import Template

welcome = Template("Hello $name. Your ID is $ID")

user = “Frank”

ID = “20403”

print(welcome.substitute(name=user,ID=ID))

 

This code gives the output:

Hello Frank. Your ID is 20403. 

 

#4 Using F-strings 

Using the f string is the most straightforward and simple way to interpolate strings. 

If you're wondering why it's called an f string, it's because the letter f is placed before the quotes. This method was introduced to Python after version 3.6, allowing you to insert expressions, variables, and function calls between curly braces directly. So, the f string method removes the need for format specifiers and explicit string concatenation.

Let's assume you want to greet every user that uses a program. You can do it by writing f "Hello." Here's the syntax of this method:

f"string literal {expression}"

 

Here's an example involving the f string method:

name = “Frank”

ID = “20403”

print(f”Hello {name}. Your ID is {ID}”)

 

This code gives the output:

Hello Frank. Your ID is 20403. 

 

String Interpolation vs. Concatenation

Most beginner programmers know concatenation as the primary way to combine strings or variables. String interpolation serves the same purpose but offers different levels of efficiency, flexibility, and readability.

String interpolation involves a clear and concise syntax, whether done using the f string method or any other method. It directly inserts variables into strings without needing explicit concatenation.

In contrast, concatenation involves combining strings and variables using the '+' operator. While simple, it can be less readable, especially with many variables or complex formatting needs.

Advantages of String Interpolation

  1. Readability: Interpolated strings are easier to read and shorter because variables go directly into the string.
  2. Flexibility: Interpolation supports math operations, complex expressions, and function calls within the string.
  3. Formatting: It offers format options to control how values are shown, like setting precision or formatting numbers.
  4. Efficiency: Interpolation is usually faster than concatenation because it doesn't create extra string objects unnecessarily.

Conclusion: Which Method Should You Use?

In Python, string interpolation is a common task in which we must dynamically change a string's value. 

There are four ways to do this: using the % sign, the format function, the Template class, or f strings. 

The % sign method isn't preferred because it makes the code less readable, while f strings are the most preferred method because they're easier to use and make the code more readable.