F”YES, {f}-string!”

Anastasia Kharina
4 min readSep 11, 2019

--

Photo by Jon Tyson on Unsplash

Growing up physically rewinding my cassette tapes with a pencil and flipping them to listen to ‘side B’, I sometimes stop myself from making snarky comments about the younger generations who only think “rewind” as a button and not an act. Those “What does ‘tape’ even mean?” memes make me really itchy.

But now I know how it feels being ‘the new generation’. I started learning to use Python well after the release of Python 3.6 in 2015. As such, I’ve only used the practical way of Python’s literal string interpolation, AKA f-string, and never needed to learn the other, earlier, ways of string formatting. So in a gesture of tipping my hat to all my Python seniors, I decided to look deeper into the magic of f-string and see how it compares to the ‘old-school’ ways.

First, let’s look at how my code looks and reads using f-string (or F-string — yes, that works too), and compare them to %-formatting and str.format():

Output:
Spock is 88 years old and works for Starfleet.
Spock is 88 years old and works for Starfleet.
Spock is 88 years old and works for Starfleet.

Both %-formatting and str.format() examples shown above look simple enough, but imagine working with longer sentences and calling many more variables. Both ways, compared to f-string, are more verbose and could lead to more errors.

With f-string, all I need to remember is to put an “f” outside of my intended string, right before the quotation mark. Variable names can be used directly inline, so long as they are placed inside {curly brackets}. This means there is no need to sort all the variables in my head as I write and read the code, and try to figure out which variable goes to which bracket or %s. My code reads *almost* like a real sentence with f-string, which probably means other people can read it better, too.

Easier on the eyes, check. But is it also easier on your machine? Let’s time its performance by printing the above sentence a million times:

Output: 
time_fstring = 0.18332997200195678
time_sform = 0.21929123399604578
time_strf = 0.32224987899826374
f-string is 1.5 times faster than %-formatting
f-string is 1.8 times faster than str.format()

It sure is faster! OK great, let’s see what else we can do with f-string:

Work with dictionaries

F-string allows us to call items of a dictionary directly in the brackets, as shown below. The only thing is to make sure to use different quotations for marking the f-string and the keys of the dictionary.

Note also below :

  • (Capital) F also works to mark an f-string
  • We can call string formatting methods inside the brackets. The word “captain” is lower-cased in the example.
Output:
James T. Kirk is 35 years old and he is the captain.

Call expressions and get support for various formatting

See our peach pie example below, on how f-string allows us to call mathematical expressions AND pass formatting commands at the same time. Note how we capitalize the word “peach”, round the price of each slice to 1 decimal point, show 5 decimal point of each person’s part of the pie, and add a comma separator to the cost of 19 pies.

This example only scratches the surface of Python’s numeric formatting. Check out my colleague Andrea Koltai’s complete guide!

Output:
One slice of PEACH pie costs $16.2
If 19 people chip in for a whole pie, each will get 5.26316%
One pie normally feeds 8 people and would leave 11 people in our group hungry
If each person want a whole pie, we have to collect $2,470
The word 'peach' has 5 letters

Call user-defined functions:

F-string allows us to call a function inline, including user-defined functions and anonymous (or lambda-) functions. Pretty cool.

Output:
When you multiply 3 and 5 you get 15
When you multiply 5 and 777 you get 3,885

We’ve concluded that f-string is pretty great. It’s intuitive, functional, and fast, and I really cannot imagine a day when I will prefer to use other, older, ways of forming and formatting strings.

BUT (there’s always a but), in practice, there will be times when someone I collaborate with uses an older version of Python for one reason or another, or when I need to make sure that my code is back-compatible with Python2. When, and only when, that day comes: we shall revert back to

print(‘the {} way of doing {}’.format(‘old’, ‘things’).

Until then, f-string all the way! F”yeah.”

Further reading on this topic: PEP 498 — Literal String Interpolation

--

--