Python-bloggers

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

This article was first published on python – Better Data Science , and kindly contributed to python-bloggers. (You can report issue about the content on this page here)
Want to share your content on python-bloggers? click here.

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

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

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, ‘mark@email.com’),
    (‘Bob’, 27, ‘bob@email.com’),
    (‘Judy’, 23, ‘judy@email.com’)
]

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)

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:

Image 3 – 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)

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:

Image 5 – 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.


The post Introducing f-Strings - The Best Option for String Formatting in Python appeared first on Better Data Science.

To leave a comment for the author, please follow the link and comment on their blog: python – Better Data Science .

Want to share your content on python-bloggers? click here.
Exit mobile version