Python 3.12 Preview: More Intuitive and Consistent F-Strings
Every new Python version brings many changes, updates, fixes, and new features. Python 3.12 will be the next minor version and is now in the beta phase. In this version, the core team has been working intensely to formalize and improve the syntax and behavior of one of the most popular Python features: f-strings.
F-strings, short for formatted strings, are string literals prefixed by either a lowercase or uppercase letter F. These strings provide a concise and clean syntax that allows the interpolation of variables and expressions.
In this tutorial, you’ll learn about:
- Limitations of f-strings in Python versions before 3.12
- Advantages of formalizing the f-string syntax
- New capabilities and features of f-strings in Python 3.12
- Formalization as the key to better error messages for f-strings
To get the most out of this tutorial, you should be familiar with the string data type, as well as with f-strings and string interpolation.
You’ll find many other new features, improvements, and optimizations in Python 3.12. The most relevant ones include the following:
- Ever better error messages
- Support for the Linux
perf
profiler - Support for subinterpreters
- Improved static typing features
Go ahead and check out what’s new in the changelog for more details on these and other features.
Free Bonus: Click here to download your sample code for a sneak peek at Python 3.12, coming in October 2023.
F-Strings Had Some Limitations Before Python 3.12
You can use Python’s f-strings for string formatting and interpolation. An f-string is a string literal prefixed with the letter F, either in uppercase or lowercase. This kind of literal lets you interpolate variables and expressions, which Python evaluates to produce the final string.
F-strings have gained a lot of popularity in the Python community since their introduction in Python 3.6. People have embraced them with enthusiasm, turning them into a standard in modern Python programming. The reasons? They provide a concise and readable syntax that allows you to format strings and interpolate variables and expressions without needing the .format()
method or the old-style string formatting operator (%
).
However, to introduce f-strings, the CPython core development team had to decide how to implement them, especially how to parse them. As a result, f-strings came with their own parsing code. In other words, CPython has a dedicated parser for f-strings. Because of this, the f-string grammar isn’t part of the official Python grammar.
From the core developers’ point of view, this implementation decision implies considerable maintenance costs because they have to manually maintain a separate parser. On the other hand, not being part of the official grammar means that other Python implementations, such as PyPy, can’t know if they’ve implemented f-strings correctly.
However, the most important burden is on the user’s side. From the user’s perspective, the current f-string implementation imposes some limitations:
- Reusing quotes or string delimiters isn’t possible.
- Embedding backslashes isn’t possible, which means you can’t use escape characters.
- Adding inline comments is forbidden.
- Nesting of f-strings is limited to the available quoting variations in Python.
PEP 536 lists these limitations. However, exploring them with a few small examples will help you understand how they can affect your use of f-strings in your Python code.
Note: The examples that you’ll see in this section use Python 3.11. If you have a lower Python version installed, then you may get different output.
First, say that you need to interpolate a dictionary key in an f-string. If you try the following code, then you’ll get an error:
>>> employee = {
... "name": "John Doe",
... "age": 35,
... "job": "Python Developer",
... }
>>> f"Employee: {employee["name"]}"
File "", line 1
f"Employee: {employee["name"]}"
^^^^
SyntaxError: f-string: unmatched '['
In this example, you try to interpolate the employee name in your f-strings. However, you get an error because the double quotes around the "name"
key break the string literal. To work around this, you need to use a different type of quotation mark to delimit the key:
>>> f"Employee: {employee['name']}"
'Employee: John Doe'
Now you use double quotes for the f-string and single quotes for the dictionary key. Your code works now, but having to switch quotes can get annoying at times.
The second limitation of f-strings is that you can’t use backslash characters in embedded expressions. Consider the following example, where you try to concatenate strings using the newline (n
) escape sequence:
>>> words = ["Hello", "World!", "I", "am", "a", "Pythonista!"]
>>> f"{'n'.join(words)}"
File "", line 1
f"{'n'.join(words)}"
^
SyntaxError: f-string expression part cannot include a backslash
Read the full article at https://realpython.com/python312-f-strings/ »
[ Improve Your Python With 🐍 Python Tricks 💌 – Get a short & sweet Python Trick delivered to your inbox every couple of days. >> Click here to learn more and see examples ]