Python 3 string formatters
Python 3 string formatters
Mark as Completed
Tweet Share Email
Table of Contents
Remove ads
Watch Now This tutorial has a related video course created by the Real Python team.
Watch it together with the written tutorial to deepen your understanding: Python
3's f-Strings: An Improved String Formatting Syntax
As of Python 3.6, f-strings are a great new way to format strings. Not only are they
more readable, more concise, and less prone to error than other ways of
formatting, but they are also faster!
By the end of this article, you will learn how and why to start using f-strings today.
But first, here’s what life was like before f-strings, back when you had to walk to
school uphill both ways in the snow.
Remove ads
This is the OG of Python formatting and has been in the language since the very
beginning. You can read more in the Python docs. Keep in mind that %-formatting
is not recommended by the docs, which contain the following note:
“The formatting operations described here exhibit a variety of quirks that lead to a
number of common errors (such as failing to display tuples and dictionaries
correctly).
Using the newer formatted string literals or the str.format() interface helps avoid
these errors. These alternatives also provide more powerful, flexible and extensible
approaches to formatting text.” (Source)
How to Use %-formatting
String objects have a built-in operation using the % operator, which you can use to
format strings. Here’s what that looks like in practice:
>>>
>>>
>>>
This newer way of getting the job done was introduced in Python 2.6. You can
check out A Guide to the Newer Python String Format Techniques for more info.
>>>
>>>
>>>
>>>
Also called “formatted string literals,” f-strings are string literals that have an f at
the beginning and curly braces containing expressions that will be replaced with
their values. The expressions are evaluated at runtime and then formatted using
the __format__ protocol. As always, the Python docs are your friend when you want
to learn more.
Here are some of the ways f-strings can make your life easier.
Simple Syntax
The syntax is similar to the one you used with str.format() but less verbose. Look
at how easily readable this is:
>>>
>>>
Arbitrary Expressions
Because f-strings are evaluated at runtime, you can put any and all valid Python
expressions in them. This allows you to do some nifty things.
>>>
>>>
>>>
class Comedian:
def __init__(self, first_name, last_name, age):
self.first_name = first_name
self.last_name = last_name
self.age = age
def __str__(self):
return f"{self.first_name} {self.last_name} is {self.age}."
def __repr__(self):
return f"{self.first_name} {self.last_name} is {self.age}. Surprise!"
You’d be able to do this:
>>>
By default, f-strings will use __str__(), but you can make sure they
use __repr__() if you include the conversion flag !r:
>>>
>>> f"{new_comedian}"
'Eric Idle is 74.'
>>> f"{new_comedian!r}"
'Eric Idle is 74. Surprise!'
If you’d like to read some of the conversation that resulted in f-strings supporting
full Python expressions, you can do so here.
Remove ads
Multiline f-Strings
>>>
>>>
>>> message = (
... f"Hi {name}. "
... "You are a {profession}. "
... "You were in {affiliation}."
... )
>>> message
'Hi Eric. You are a {profession}. You were in {affiliation}.'
If you don’t put an f in front of each individual line, then you’ll just have regular,
old, garden-variety strings and not shiny, new, fancy f-strings.
If you want to spread strings over multiple lines, you also have the option of
escaping a return with a \:
>>>
>>>
Speed
f-strings are faster than both %-formatting and str.format(). As you already saw, f-
strings are expressions evaluated at runtime rather than constant values. Here’s an
excerpt from the docs:
>>>
>>>
However, that wasn’t always the case. When they were first implemented, they had
some speed issues and needed to be made faster than str.format(). A
special BUILD_STRING opcode was introduced.
Remove ads
Quotation Marks
You can use various types of quotation marks inside the expressions. Just make
sure you are not using the same type of quotation mark on the outside of the f-
string as you are using in the expression.
>>>
>>>
>>>
>>>
>>>
Dictionaries
Speaking of quotation marks, watch out when you are working with dictionaries. If
you are going to use single quotation marks for the keys of the dictionary, then
remember to make sure you’re using double quotation marks for the f-strings
containing the keys.
>>>
>>>
Remove ads
Braces
In order to make a brace appear in your string, you must use double braces:
>>>
>>>
>>>
Backslashes
As you saw earlier, it is possible for you to use backslash escapes in the string
portion of an f-string. However, you can’t use backslashes to escape in the
expression part of an f-string:
>>>
>>>
Inline Comments
Expressions should not include comments using the # symbol. You’ll get a syntax
error:
>>>
According to the Zen of Python, when you need to decide how to do something,
then “[t]here should be one– and preferably only one –obvious way to do it.”
Although f-strings aren’t the only possible way for you to format strings, they are in
a great position to become that one obvious way to get the job done.
Further Reading
If you’d like to read an extended discussion about string interpolation, take a look
at PEP 502. Also, the PEP 536 draft has some more thoughts about the future of f-
strings.