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:
- The Modulo Operator, %
- 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:
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:
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:
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:
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:
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:
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:
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:
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:
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:
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:
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:
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:
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.