Introducing f-Strings — The Best Option for String Formatting in Python | by Dario Radečić | Dec, 2020

[ad_1]


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:

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:

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.

Read More …

[ad_2]


Write a comment