Skip to content

Python String Interpolation: Effortlessly Combine Strings and Variables

[

Python’s F-String for String Interpolation and Formatting

by Joanna Jablonski Oct 18, 2023 68 Comments

Python f-strings provide a quick way to interpolate and format strings. They’re readable, concise, and less prone to error than traditional string interpolation and formatting tools, such as the .format() method and the modulo operator (%) . An f-string is also a bit faster than those tools!

By the end of this tutorial, you’ll know why f-strings are such a powerful tool that you should learn and master as a Python developer.

In this tutorial, you’ll learn how to:

  • Interpolate values, objects, and expressions into your strings using f-strings
  • Format f-strings using Python’s string formatting mini-language
  • Leverage some cool features of f-strings in Python 3.12 and beyond
  • Decide when to use traditional interpolation tools instead of f-strings

To get the most out of this tutorial, you should be familiar with Python’s string data type. It’s also be beneficial to have experience with other string interpolation tools like the modulo operator (%) and the .format() method.

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 string interpolation operator (%), or modulo operator
  2. The str.format() method

You’ll get a refresher on these two string interpolation tools in the following sections. You’ll also learn about the string formatting capabilities they provide.

The Modulo Operator, %

The modulo operator (%) allows you to insert values into placeholders in a string literal. Here’s a simple example:

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

Output:

My name is Alice and I am 25 years old.

In the example above, the %s is a placeholder for a string, and the %d is a placeholder for an integer. The values of name and age are passed to the modulo operator as a tuple (name, age).

The str.format() Method

The str.format() method provides a more flexible way to interpolate values into a string. Instead of using placeholders with % , you can use {} and pass the values as arguments to the format() method. Here’s an example:

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

Output:

My name is Alice and I am 25 years old.

In this example, {} is a placeholder that will be replaced with the corresponding values passed as arguments to the format() method.

Doing String Interpolation With F-Strings in Python

Python 3.6 introduced a new way to interpolate strings using formatted string literals, also known as f-strings. An f-string is prefixed with the letter f and is followed by a string literal that may contain placeholders. The placeholders are enclosed in curly braces {} and can hold expressions, variables, or even complex expressions. Let’s see it in action:

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

Output:

My name is Alice and I am 25 years old.

The example above demonstrates the basic usage of an f-string. You can see that instead of using % or .format(), the f-string directly interpolates the values of name and age into the string.

Interpolating Values and Objects in F-Strings

F-strings provide a straightforward way to interpolate values and objects into strings. You can use expressions and refer to variables directly within the placeholders. Here’s an example:

price = 29.99
quantity = 3
total = f"The total cost is ${price * quantity:.2f}."
print(total)

Output:

The total cost is $89.97.

In this example, the expression price * quantity is evaluated and the result is formatted with two decimal places using :.2f. The result is then interpolated into the string between the curly braces {}.

Embedding Expressions in F-Strings

In addition to simple values and objects, you can embed expressions directly into f-strings. This allows you to perform calculations, call functions, and perform any other operations necessary to generate a desired result. Let’s take a look at an example:

import datetime
today = datetime.date.today()
message = f"Today is {today.strftime('%A, %B %d, %Y')}."
print(message)

Output:

Today is Sunday, October 01, 2023.

In this example, the expression today.strftime('%A, %B %d, %Y') is evaluated to retrieve the current date and format it as a string. The resulting string is then interpolated into the f-string.

Formatting Strings With Python’s F-String

F-strings can be further formatted using Python’s string formatting mini-language. This language allows you to specify various formatting options for the interpolated values and objects. Some common formatting options include specifying the width, alignment, precision, and type of the value. Let’s take a look at a few examples:

pi = 3.141592653589793
formatted_pi = f"Value of pi: {pi:.2f}"
print(formatted_pi)
name = "Alice"
formatted_name = f"Name: {name:>10}"
print(formatted_name)
age = 25
formatted_age = f"Age: {age:03d}"
print(formatted_age)
is_old = True
formatted_is_old = f"Is old? {is_old}"
print(formatted_is_old)

Output:

Value of pi: 3.14
Name: Alice
Age: 025
Is old? True

In the examples above, :.2f specifies that the value should be formatted as a float with two decimal places. :>10 aligns the value to the right with a width of 10 characters. :03d specifies that the integer should be zero-padded and have a width of 3 characters. Finally, {is_old} simply prints the boolean value without any specific formatting.

Formatting options can be combined and customized to achieve the desired output.

Other Relevant Features of F-Strings

F-strings offer additional features beyond simple string interpolation and formatting. These features can enhance your code readability, make debugging easier, and provide better performance compared to traditional interpolation tools.

Using an Object’s String Representations in F-Strings

F-strings automatically call the __str__() and __repr__() methods of objects that are interpolated into a string. This allows you to easily include the string representation of an object in an f-string. Here’s an example:

class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __repr__(self):
return f"Person(name='{self.name}', age={self.age})"
person = Person("Alice", 25)
message = f"Person: {person}"
print(message)

Output:

Person: Person(name='Alice', age=25)

In this example, the Person object is interpolated into the string using the default __repr__() method. This method returns a string representation of the object that includes its name and age attributes.

Self-Documenting Expressions for Debugging

F-strings support the automatic evaluation of expressions and variables, making it easier to debug and understand your code. Rather than needing to add separate print statements or temporary variables, you can include expressions directly in the f-string. For example:

x = 5
y = 7
result = f"The sum of {x} and {y} is {x + y}"
print(result)

Output:

The sum of 5 and 7 is 12

In this example, the x + y expression is evaluated and automatically interpolated into the string. This allows you to see the result of the expression without using separate print statements or temporary variables.

Comparing Performance: F-String vs Traditional Tools

F-strings are not only more readable and concise, but they also offer better performance compared to traditional string interpolation and formatting tools. The exact performance gain depends on the specific use case, but generally, f-strings are faster.

Upgrading F-Strings: Python 3.12 and Beyond

Python 3.12 introduced several new features and improvements to f-strings. These enhancements further improve the readability and flexibility of f-strings.

Using Quotation Marks

In Python 3.12 and beyond, you can use single quotation marks (’ ’) or triple single quotation marks (''' ''') within f-strings without escaping. This allows for more natural and cleaner-looking code. For example:

name = "Alice"
message = f"{name} said, 'Hello, world!'"
print(message)

Output:

Alice said, 'Hello, world!'

In this example, the single quotation marks within the f-string are not escaped and are used naturally in the string.

Using Backslashes

In addition to quotation marks, you can also use backslashes () within f-strings without escaping. This makes it easier to include special characters or escape sequences in your strings. Here’s an example:

message = f"Escape sequence: \n"
print(message)

Output:

Escape sequence:

In this example, the backslash and the ‘n’ character are not escaped and are interpreted as an escape sequence producing a new line.

Writing Inline Comments

Starting from Python 3.12, you can include comments within f-strings by enclosing them in curly braces (# {}). This allows you to add explanatory comments directly within the f-string. Here’s an example:

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

Output:

My name is Alice and I am 25 years old. # This is a comment

In this example, the comment (# This is a comment) is included directly within the f-string and is not interpreted as part of the string itself.

Deciphering F-String Error Messages

Python 3.12 introduced better error messages for f-strings. These error messages provide more precise information about what went wrong in case of a syntax error or incorrect usage of an f-string. The improved error messages make debugging easier and faster.

Using Traditional String Formatting Tools Over F-Strings

F-strings are powerful and provide many benefits, but there are scenarios where traditional string interpolation and formatting tools, such as the modulo operator (%) and the str.format() method, may be more suitable.

Dictionary Interpolation

If you have a large number of values to interpolate into a string, and those values are stored in a dictionary, using the .format() method or the modulo operator may be more convenient. Here’s an example:

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

Output:

My name is Alice and I am 25 years old.

In this example, the dictionary person contains the values to be interpolated into the string. By using the {name} and {age} placeholders and passing the dictionary as keyword arguments using **person, you can easily interpolate the values.

Lazy Evaluation in Logging

Logging can be resource-intensive, especially when expensive computations need to be performed to generate the log message. In these cases, using traditional interpolation tools can help. Here’s an example:

import logging
x = 10
y = 20
logger = logging.getLogger(__name__)
logger.debug("x: %s, y: %s", x, y)

In this example, the logger.debug() method uses the modulo operator (%) to interpolate the values of x and y. However, it does this only if the logging level is set to debug. This way, the expensive computation is avoided when logging.debug() is not called.

SQL Database Queries

When constructing SQL queries dynamically, traditional interpolation tools like the modulo operator (%) can help you build the query string. However, be aware of the risks of SQL injection and make sure to properly sanitize and validate any user input.

Internationalization and Localization

If your application needs to support multiple languages and localization, using traditional string formatting tools can make it easier to handle translations and language-specific formatting rules. Python provides the gettext module and other libraries specifically designed for internationalization and localization.

Converting Old String Into F-Strings Automatically

If you have existing codebases that use traditional string interpolation tools like the modulo operator (%) or the .format() method, you can use the tools like 2to3 or futurize to automatically convert them to f-strings. These tools can save you a lot of time and effort by automating the conversion process.

Key Takeaways

  • F-strings are a powerful and efficient way to interpolate and format strings in Python.
  • F-strings offer a more readable and concise syntax compared to traditional interpolation tools like the modulo operator (%) and the .format() method.
  • F-strings can interpolate values, objects, expressions, and even complex expressions directly into string literals.
  • F-strings can be further formatted using Python’s string formatting mini-language.
  • F-strings offer additional features like automatic evaluation of expressions, self-documenting code, and improved performance over traditional string interpolation tools.
  • Python 3.12 introduced new enhancements to f-strings, including support for using quotation marks, backslashes, and inline comments within f-strings.
  • Traditional string interpolation tools may still be more suitable for certain scenarios, such as dictionary interpolation, lazy evaluation in logging, SQL database queries, and internationalization and localization.
  • Automated tools like 2to3 and futurize can help convert existing codebases from traditional interpolation tools to f-strings.

Now that you have learned about f-strings, you can start using them in your Python code to simplify string interpolation and formatting!