Skip to content

Effortlessly Mastering Python Interpolated Strings

[

Python’s F-String for String Interpolation and Formatting

by Joanna Jablonski Oct 18, 2023

Interpolating and Formatting Strings Before Python 3.6

Before Python 3.6, you had two main tools for interpolating values, variables, and expressions inside string literals:

  1. The Modulo Operator, %
  2. The str.format() Method

The Modulo Operator, %

The modulo operator, %, allows you to interpolate values into a string. You use a formatting string with placeholders, represented by % followed by a format specifier. For example:

name = "Alice"
age = 25
message = "My name is %s and I am %d years old." % (name, age)
print(message)

In this example, the placeholders %s and %d are replaced with the values of the variables name and age, respectively.

The str.format() Method

The str.format() method provides a more flexible way of interpolating values into a string. Instead of using placeholders, you can use curly braces {} and supply the values as arguments to the format() method. For example:

name = "Alice"
age = 25
message = "My name is {} and I am {} years old.".format(name, age)
print(message)

In this example, the curly braces {} are replaced with the values of the variables name and age, respectively.

Doing String Interpolation With F-Strings in Python

F-strings, short for formatted string literals, were introduced in Python 3.6 as a convenient and concise way to interpolate values into a string.

Interpolating Values and Objects in F-Strings

To interpolate values and objects into an f-string, you enclose the expression in curly braces {} and prefix the f-string with the letter ‘f’. For example:

name = "Alice"
age = 25
message = f"My name is {name} and I am {age} years old."
print(message)

In this example, the expressions {name} and {age} are replaced with the values of the variables name and age, respectively.

Embedding Expressions in F-Strings

F-strings also allow you to embed expressions directly into the string. You enclose the expression in curly braces {} and prefix the expression with an equal sign (=). For example:

result = f"The result of 5 + 4 is {5 + 4}."
print(result)

In this example, the expression {5 + 4} is evaluated and the result is embedded into the string.

Formatting Strings With Python’s F-String

Just like the previous interpolation tools, you can format f-strings using Python’s string formatting mini-language. The mini-language provides a concise and powerful way to control the formatting of values within the string.

To format a value within an f-string, you include a colon (:) followed by the format specifier after the expression inside the curly braces {}. For example:

pi = 3.14159
formatted = f"The value of pi is approximately {pi:.2f}."
print(formatted)

In this example, the format specifier :.2f formats the value of the variable pi as a floating-point number with 2 decimal places.

You can refer to the Python documentation for a detailed explanation of all the available format specifiers and the different formatting options.

Other Relevant Features of F-Strings

In addition to value interpolation and formatting, f-strings provide some other useful features that make them even more powerful.

Using an Object’s String Representations in F-Strings

In Python, objects can define their own string representations by implementing the str() and repr() methods. F-strings automatically use these string representations when interpolating objects. For example:

class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __str__(self):
return f"{self.name} (Age: {self.age})"
def __repr__(self):
return f"Person({self.name}, {self.age})"
person = Person("Alice", 25)
message = f"{person}" # Uses the __str__() method
print(message)
representation = f"{person!r}" # Uses the __repr__() method
print(representation)

In this example, the f-strings {person} and {person!r} automatically call the str() and repr() methods of the Person object.

Self-Documenting Expressions for Debugging

F-strings allow you to include expressions directly in the string for debugging purposes. By including the expression inside the curly braces {} preceded by an exclamation mark (!), the expression will be evaluated and the result will be included in the string. For example:

x = 5
y = 10
message = f"The result of {x} + {y} is {x + y = }."
print(message)

In this example, the expression {x + y =} includes the result of the addition operation (x + y) along with its corresponding expression x + y.

Comparing Performance: F-String vs Traditional Tools

In terms of performance, f-strings are faster than the traditional interpolation tools, such as the modulo operator (%) and the str.format() method. F-strings achieve this by reducing the number of function calls and avoiding unnecessary conversions. However, the performance difference may be negligible for most applications.

Upgrading F-Strings: Python 3.12 and Beyond

Python 3.12 introduced several new features and improvements to f-strings.

Using Quotation Marks

One of the new features in Python 3.12 is the ability to use quotation marks inside f-strings without needing to escape them. For example:

name = "Alice"
message = f"She said, 'My name is {name}.'"
print(message)

In earlier versions of Python, you would need to escape the quotation marks like this: f”She said, ‘My name is {name}.‘”

Using Backslashes

Python 3.12 also allows backslashes to be used inside f-strings without needing to be escaped. This makes it easier to include file paths or regular expressions in f-strings. For example:

path = r"C:\Users\Alice\Desktop\file.txt"
message = f"The file path is {path}."
print(message)

In earlier versions of Python, you would need to double the number of backslashes like this: path = “C:\Users\Alice\Desktop\file.txt”

Writing Inline Comments

Another improvement in Python 3.12 is the ability to write inline comments inside f-strings using the # symbol. This allows you to include additional notes or reminders directly within the string. For example:

name = "Alice"
message = f"My name is {name}. # This is a comment"
print(message)

Deciphering F-String Error Messages

Python 3.12 also introduced more informative error messages for f-strings. When an f-string contains a syntax error, the error message now includes the position of the error and a clearer explanation of the problem.

Using Traditional String Formatting Tools Over F-Strings

While f-strings provide a powerful and convenient way to interpolate and format strings, there are still some cases where traditional interpolation tools may be more suitable.

Dictionary Interpolation

If you have a dictionary of values that you want to interpolate into a string, using the str.format() method may be more appropriate than f-strings. With str.format(), you can pass the dictionary as an argument and refer to its keys inside the string. For example:

person = {"name": "Alice", "age": 25}
message = "My name is {name} and I am {age} years old.".format(**person)
print(message)

In this example, the keys name and age from the dictionary are used as placeholders inside the string.

Lazy Evaluation in Logging

When logging messages, it’s sometimes desirable to delay the evaluation of expressions until it’s certain that the message will actually be logged. Traditional string interpolation tools, such as the modulo operator (%), support lazy evaluation. For example:

import logging
logger = logging.getLogger()
name = "Alice"
age = 25
message = "My name is %s and I am %d years old."
if logger.isEnabledFor(logging.INFO):
logger.info(message, name, age)

In this example, the message is evaluated and formatted only if the logger has been enabled for the INFO level.

SQL Database Queries

When constructing SQL queries dynamically, using string interpolation tools like the modulo operator (%) or str.format() may be safer than using f-strings. F-strings may introduce the risk of SQL injection if the query includes user-supplied input. For example:

username = "Alice"
password = "password123"
query = "SELECT * FROM users WHERE username = '%s' AND password = '%s'" % (username, password)

In this example, the values of the variables username and password are directly interpolated into the SQL query using the modulo operator (%).

Internationalization and Localization

In scenarios where you need to support internationalization and localization, traditional interpolation tools like the modulo operator (%) or str.format() offer more flexibility. These tools allow you to easily swap out the format strings for different languages or locales, while f-strings require manually changing the string literals.