Python f-strings offer a concise and efficient way to interpolate variables, objects, and expressions directly into strings. By prefixing a string with f or F, you can embed expressions within curly braces ({}), which are evaluated at runtime.
This makes f-strings faster and more readable compared to older approaches like the modulo (%) operator or the string .format() method. Additionally, f-strings support advanced string formatting using Python’s string format mini-language.
By the end of this tutorial, you’ll understand that:
- An f-string in Python is a string literal prefixed with
forF, allowing for the embedding of expressions within curly braces{}. - To include dynamic content in an f-string, place your expression or variable inside the braces to interpolate its value into the string.
- An f-string error in Python often occurs due to syntax issues, such as unmatched braces or invalid expressions within the string.
- Python 3.12 improved f-strings by allowing nested expressions and the use of backslashes.
This tutorial will guide you through the features and advantages of f-strings, including interpolation and formatting. By familiarizing yourself with these features, you’ll be able to effectively use f-strings in your Python projects.
Get Your Code: Click here to download the free sample code that shows you how to do string interpolation and formatting with Python’s f-strings.
Take the Quiz: Test your knowledge with our interactive “Python's F-String for String Interpolation and Formatting” quiz. You’ll receive a score upon completion to help you track your learning progress:
Interactive Quiz
Python's F-String for String Interpolation and FormattingTest your understanding of Python f-strings, including syntax, expression embedding, type conversions, and quoting rules.
Python for Beginners Live Course: Want to practice core skills like working with strings alongside an instructor? In Real Python’s Python for Beginners live course, you build real programs in a small group, with live feedback when you get stuck. Join the waitlist to hear about the next dates.
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 string interpolation operator (
%), or modulo operator - 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 that these tools offer in Python.
The Modulo Operator (%)
The modulo operator (%) was the first tool for string interpolation and formatting in Python and has been in the language since the beginning. Here’s what using this operator looks like in practice:
>>> name = "Jane"
>>> "Hello, %s!" % name
'Hello, Jane!'
In this quick example, you use the % operator to interpolate the value of your name variable into a string literal. The interpolation operator takes two operands:
- A string literal containing one or more conversion specifiers
- The object or objects that you’re interpolating into the string literal
The conversion specifiers work as replacement fields. In the above example, you use the %s combination of characters as a conversion specifier. The % symbol marks the start of the specifier, while the s letter is the conversion type and tells the operator that you want to convert the input object into a string.
If you want to insert more than one object into your target string, then you can use a tuple. Note that the number of objects in the tuple must match the number of format specifiers in the string:
>>> name = "Jane"
>>> age = 25
>>> "Hello, %s! You're %s years old." % (name, age)
"Hello, Jane! You're 25 years old."
In this example, you use a tuple of values as the right-hand operand to %. Note that you’ve used a string and an integer. Because you use the %s specifier, Python converts both objects to strings.
You can also use dictionaries as the right-hand operand in your interpolation expressions. To do this, you need to create conversion specifiers that enclose key names in parentheses:
>>> "Hello, %(name)s! You're %(age)s years old." % {"name": "Jane", "age": 25}
"Hello, Jane! You're 25 years old."
This syntax provides a readable approach to string interpolation with the % operator. You can use descriptive key names instead of relying on the positional order of values.
When you use the % operator for string interpolation, you can use conversion specifiers. They provide some string formatting capabilities that take advantage of conversion types, conversion flags, and some characters like the period (.) and the asterisk (*). Consider the following example:
>>> "Balance: $%.2f" % 5425.9292
'Balance: $5425.93'
>>> print("Name: %s\nAge: %5s" % ("John", 35))
Name: John
Age: 35
In the first example, you use the %.2f conversion specifier to represent currency values. The f letter tells the operator to convert to a floating-point number. The .2 part defines the precision to use when converting the input. In the second example, you use %5s to align the age value five positions to the right.
Note: Formatting with the modulo operator is inspired by printf() formatting used in C and many other programming languages.
Even though the % operator provides a quick way to interpolate and format strings, it has a few issues that lead to common errors. For example, it’s difficult to interpolate tuples in your strings:
>>> "The personal info is: %s" % ("John", 35)
Traceback (most recent call last):
...
TypeError: not all arguments converted during string formatting
In this example, the operator fails to display the tuple of data because it interprets the tuple as two separate values. You can fix this issue by wrapping the data in a single-item tuple:
>>> "The personal info is: %s" % (("John", 35),)
"The personal info is: ('John', 35)"
This syntax fixes the issue, and now your string successfully shows the tuple of data. However, the syntax is hard to read, understand, and remember, isn’t it?
Another issue with the % operator is its limited formatting capabilities and the lack of support for Python’s string formatting mini-language, which provides a powerful tool to format your strings.
The str.format() Method
The str.format() method is an improvement compared to the % operator because it fixes a couple of issues and supports the string formatting mini-language. With .format(), curly braces delimit the replacement fields:
>>> name = "Jane"
>>> age = 25
>>> "Hello, {}! You're {} years old.".format(name, age)
"Hello, Jane! You're 25 years old."
For the .format() method to work, you must provide replacement fields using curly brackets. If you use empty brackets, then the method interpolates its arguments into the target string based on position.
You can manually specify the interpolation order by referencing the position of each argument to .format() using zero-based indices. For example, the code below switches the arguments to .format() in the target string:
>>> "Hello,