The world’s leading publication for data science, AI, and ML professionals.

Introducing f-Strings – The Best Option for String Formatting in Python

Meet Python's most powerful string formatting option – and master it in 5 minutes or less.

Photo by Andy Holmes on Unsplash
Photo by Andy Holmes on Unsplash

There’s a bunch of ways to handle string formatting in Python. The most recent one is with f-Strings – an improvement from the previously used techniques. Today you’ll learn 3 key reasons why f-Strings are a way to go in 2021 and beyond.

Here’s the complete list:

  • Reason #1 – f-Strings look clean
  • Reason #2 – f-Strings are faster
  • Reason #3 – f-Strings allow extensive manipulation

Reason #1 – f-Strings look clean

Including variables to print statement was always kind of a messy process. Most of the legacy code uses % syntax, which lists the variables after the text. Neat when you have a small number of variables, messy otherwise.

Here’s an example:

name = 'Mark'
city = 'New York'
age = 35
print('My name is %s, I live in %s, and I am %s years old.' % (name, city, age))

Now imagine you had 20 variables. Not so easy to maintain, is it?

Then came the .format() function. I’m sure you can see it in a lot of Python code, but it isn’t the most recent solution. It’s quite similar to the % syntax, but offers some improvements.

Here’s an example:

name = 'Mark'
city = 'New York'
age = 35
print('My name is {}, I live in {}, and I am {} years old.'.format(name, city, age))

As you can see, still not a very clean solution.

Finally, there are f-Strings. They offer by far the best way of string formating. You’ll need to put f in front of the opening string, and you’re good to go.

Here’s an example:

name = 'Mark'
city = 'New York'
age = 35
print(f'My name is {name}, I live in {city}, and I am {age} years old.')

This alone should be enough of a selling factor. But continue reading if you’re not entirely convinced.


Reason #2 – f-Strings are faster

Let’s cut to the chase right away. Interactive Python notebooks come with the %%time magic command. You can easily measure the time required to execute a code block with them.

Here’s the comparison for all three string formatting methods:

Image 1 - Speed comparison of different string
Image 1 – Speed comparison of different string

The numbers say it all.


Reason #3 – f-Strings allow extensive manipulation

Let’s make ourselves a small dataset to work with:

users = [
    ('Mark', 35, '[email protected]'),
    ('Bob', 27, '[email protected]'),
    ('Judy', 23, '[email protected]')
]

Now how would you use string formatting to print these three users? The answer is simple:

for user in users:
    print(f'{user[0]} {user[1]} {user[2]}')

The output is shown in the image below:

Image 2 - Default strings formatting (image by author)
Image 2 – Default strings formatting (image by author)

That’s literally the least creative approach to printing. You can do much more with f-Strings. For example, here’s how to specify how many spaces each variable takes:

for user in users:
    print(f'{user[0]:{6}} {user[1]:{3}} {user[2]:{20}}')

The output is shown in the image below:

Adding spaces to the output (image by author)
Adding spaces to the output (image by author)

Now we’re getting somewhere. I’d like the emails aligned to the right. You can use the > operator to do so. Here’s the code:

for user in users:
    print(f'{user[0]:{6}} {user[1]:{3}} {user[2]:>{20}}')

The output is shown below:

Image 4 - String formatting alignment (image by author)
Image 4 – String formatting alignment (image by author)

Better. Still, one thing you can do. You can fill in the whitespaces with f-Strings. Specify the filling character right after the variable reference. Here’s an example of how to fill whitespace on both left and right side with a dash:

for user in users:
    print(f'{user[0]:-<{6}} {user[1]:-<{3}} {user[2]:->{20}}')

And here are the results:

Filling whitespace (image by author)
Filling whitespace (image by author)

That’s enough to convince you f-Strings are a way to go in 2021 and beyond. Let’s wrap things up next.


Conclusion

In a nutshell, f-Strings provide a cleaner and easier to manage way for formatting strings. Plus, they are a lot faster. You should use them whenever possible if you have access to Python 3.6 or a newer version. Earlier versions don’t support f-Strings, unfortunately.

What’s your favorite f-Strings feature? Let me know in the comments below.


Loved the article? Become a Medium member to continue learning without limits. I’ll receive a portion of your membership fee if you use the following link, with no extra cost to you.

Join Medium with my referral link – Dario Radečić


Join my private email list for more helpful insights.


Related Articles