Skip to content

How to Easily Fix How to Use Questions in Python

[

Python’s F-String for String Interpolation and Formatting

by Joanna Jablonski Oct 18, 2023

Table of Contents

  • Interpolating and Formatting Strings Before Python 3.6
    • The Modulo Operator, %
    • The str.format() Method
  • Doing String Interpolation With F-Strings in Python
    • Interpolating Values and Objects in F-Strings
    • Embedding Expressions in F-Strings
  • Formatting Strings With Python’s F-String
  • Other Relevant Features of F-Strings
    • Using an Object’s String Representations in F-Strings
    • Self-Documenting Expressions for Debugging
    • Comparing Performance: F-String vs Traditional Tools
  • Upgrading F-Strings: Python 3.12 and Beyond
    • Using Quotation Marks
    • Using Backslashes
    • Writing Inline Comments
    • Deciphering F-String Error Messages
  • Using Traditional String Formatting Tools Over F-Strings
    • Dictionary Interpolation
    • Lazy Evaluation in Logging
    • SQL Database Queries
    • Internationalization and Localization
  • Converting Old String Into F-Strings Automatically
  • Key Takeaways

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

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 in Python 3.6 and how f-strings provide a better alternative.

The Modulo Operator, %

The modulo operator, %, was used to interpolate variables and values into a string. It allowed you to include placeholders inside the string, marked by a % sign, followed by a letter or symbol that represented the type of value that would be interpolated.

Here’s an example:

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

Output:

My name is Alice and I'm 25 years old.

In this example, the %s placeholder is used for a string value (name) and the %d placeholder is used for an integer value (age). The values to be interpolated are provided within the parentheses after the % operator.

The str.format() Method

The str.format() method was introduced in Python 2.6 as a more flexible and powerful way to interpolate values into strings.

Here’s an example:

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

Output:

My name is Alice and I'm 25 years old.

In this example, the {} placeholders are used to indicate where the values should be interpolated. The values are passed as arguments to the format() method.

Doing String Interpolation With F-Strings in Python

Python 3.6 introduced f-strings as a new way to interpolate and format strings. F-strings offer a more concise and readable syntax compared to the modulo operator and the str.format() method.

Interpolating Values and Objects in F-Strings

F-strings allow you to directly insert the values and objects you want to interpolate into the string by placing them inside curly braces {}. You can include variables, expressions, and even function calls inside the curly braces.

Here’s an example:

name = "Alice"
age = 25
sentence = f"My name is {name} and I'm {age} years old."
print(sentence)

Output:

My name is Alice and I'm 25 years old.

In this example, the f before the opening quotation mark denotes that it is an f-string. The variables name and age are directly interpolated into the string by placing them inside curly braces {}.

Embedding Expressions in F-Strings

You can also include expressions inside f-strings by wrapping them in curly braces {}. The expression will be evaluated and the result will be interpolated into the string.

Here’s an example:

name = "Alice"
age = 25
sentence = f"My name is {name.upper()} and I'll be {age + 1} next year."
print(sentence)

Output:

My name is ALICE and I'll be 26 next year.

In this example, the name.upper() expression is evaluated to uppercase the value of the name variable. The age + 1 expression adds 1 to the value of the age variable.

Formatting Strings With Python’s F-String

In addition to interpolation, f-strings also support string formatting using Python’s string formatting mini-language. This allows you to control the appearance and presentation of the interpolated values in your string.

Here’s an example:

name = "Alice"
age = 25
sentence = f"My name is {name.lower():^10} and I'm {age:03d} years old."
print(sentence)

Output:

My name is alice and I'm 025 years old.

In this example, the {name.lower():^10} specifies that the name value should be converted to lowercase and centered within a field of width 10. The age:03d specifies that the age value should be displayed with leading zeros, as a three-digit number.

Other Relevant Features of F-Strings

F-strings not only provide a concise and readable syntax for string interpolation, but they also offer additional features that can be useful in certain scenarios.

Using an Object’s String Representations in F-Strings

When interpolating objects into f-strings, Python automatically calls the __str__() method of the objects to retrieve their string representation.

Here’s an example:

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

Output:

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

In this example, the Person class defines a __str__() method that returns a formatted string representation of the object. When the person object is interpolated into the f-string, Python automatically calls the __str__() method to retrieve the string representation of the object.

Self-Documenting Expressions for Debugging

F-strings support the use of self-documenting expressions by embedding simple expressions that provide additional information about the context or value being interpolated. This can be useful for debugging purposes.

Here’s an example:

name = "Alice"
age = 25
sentence = f"My name is {name!r} and I'm {age:.1f} years old."
print(sentence)

Output:

My name is 'Alice' and I'm 25.0 years old.

In this example, the {name!r} specifies that the name value should be represented as a string literal enclosed in single quotes. The {age:.1f} specifies that the age value should be displayed as a floating-point number with one digit after the decimal point.

Comparing Performance: F-String vs Traditional Tools

F-strings are not only concise and readable, but they are also faster than traditional string interpolation tools like the modulo operator and the str.format() method. This makes them a more efficient choice, especially in performance-critical scenarios.

A benchmark comparison between f-strings and the modulo operator can be found in the official Python documentation.

Upgrading F-Strings: Python 3.12 and Beyond

Python 3.12 introduces new features and enhancements for f-strings, making them even more powerful and flexible.

Using Quotation Marks

In Python 3.12, you’ll be able to use either single or double quotation marks for your f-strings, providing more flexibility in writing and formatting your strings.

Here’s an example:

name = "Alice"
age = 25
sentence = f'My name is {name} and I'm {age} years old.'
print(sentence)

Output:

My name is Alice and I'm 25 years old.

In this example, single quotation marks are used to enclose the f-string. This can be handy when the string itself contains double quotation marks.

Using Backslashes

Python 3.12 also allows the use of backslashes within f-strings. This makes it easier to write strings that contain special characters or escape sequences.

Here’s an example:

path = r"C:\Users\Alice\Documents"
sentence = f'The path is: {path}'
print(sentence)

Output:

The path is: C:\Users\Alice\Documents

In this example, the r before the opening quotation mark denotes a raw string. The backslashes within the f-string are treated as literal characters, allowing you to represent file paths or other strings that contain backslashes.

Writing Inline Comments

Starting from Python 3.12, you can include inline comments within f-strings by prefixing them with a # character. This can be useful for providing explanations or documenting the code within the string itself.

Here’s an example:

name = "Alice"
age = 25
sentence = f'My name is {name} and I'm {age} years old.#{name} is a common name.'
print(sentence)

Output:

My name is Alice and I'm 25 years old. #Alice is a common name.

In this example, the inline comment #Alice is a common name. provides additional information about the name value within the f-string.

Deciphering F-String Error Messages

Starting from Python 3.12, error messages related to f-strings will be improved to provide more informative and helpful information.

Using Traditional String Formatting Tools Over F-Strings

While f-strings are powerful and efficient, there may still be scenarios where using other string formatting tools, such as the modulo operator or the str.format() method, is more suitable.

Dictionary Interpolation

F-strings support interpolation of dictionaries using {key} in curly braces. However, if you need more control over the formatting or need to interpolate multiple values from a dictionary, using the str.format() method with a dictionary as the argument might be a better choice.

Lazy Evaluation in Logging

In certain scenarios, it might be more efficient to use the str.format() method or the modulo operator for string interpolation in logging statements. This is because f-strings are evaluated immediately, even if the log message isn’t going to be displayed.

SQL Database Queries

When constructing SQL queries, you might need to properly escape and format the values being interpolated. In such cases, using string formatting tools specific to SQL (like the psycopg2 package for PostgreSQL) might be more appropriate.

Internationalization and Localization

For internationalization and localization purposes, you might need to construct strings that are translated into multiple languages. In this case, using the gettext module or other localization libraries can provide more flexibility and support for different language formats.

Converting Old String Into F-Strings Automatically

If you have existing code that uses the modulo operator or the str.format() method for string interpolation, you can use tools like futurize or modernize to automatically convert the old-style strings into f-strings. This can simplify your codebase and take advantage of the benefits offered by f-strings.

Key Takeaways

F-strings provide a powerful and efficient way to interpolate and format strings in Python. They offer readability, conciseness, and performance advantages over traditional string interpolation tools. With the addition of new features in Python 3.12, f-strings become even more flexible and powerful.

In this tutorial, you’ve learned how to interpolate values, objects, and expressions into strings using f-strings, format f-strings using Python’s string formatting mini-language, and leverage some cool features of f-strings. You’ve also seen when it might be more appropriate to use traditional interpolation tools over f-strings.

Now that you have a solid understanding of f-strings, you can start using them in your Python projects to make your code more readable and efficient.