F String
F String
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.
You can read all about it in PEP 498, which was written by Eric V. Smith in August of 2015.
Simple Syntax
The syntax is similar to the one you used with str.format() but less verbose. Look at how easily
readable this is:
>>> age = 74
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.
'74'
>>> message = (
... )
>>> message
But remember that you need to place an f in front of each line of a multiline string. The following
code won’t work:
>>> message = (
... )
>>> message
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.
...
>>> message
... Hi {name}.
... """
...
>>> message
Speed
The f in f-strings may as well stand for “fast.”
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:
“F-strings provide a way to embed expressions inside string literals, using a minimal syntax. It should
be noted that an f-string is really an expression evaluated at run time, not a constant value. In
Python source code, an f-string is a literal string, prefixed with f, which contains expressions inside
braces. The expressions are replaced with their values.” (Source)
At runtime, the expression inside the curly braces is evaluated in its own scope and then put
together with the string literal part of the f-string. The resulting string is then returned. That’s all it
takes.
... age = 74
0.003324444866599663
... age = 74
0.004242089427570761
... age = 74
0.0024820892040722242
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.