Awesome Python f-strings

Learn to master the full power of the Python f-string

C05348A3-9AB8-42C9-A6E0-81DB3AC59FEB
           

The awesome power of Python f-strings

Formatted string literals - also called f-strings - have been around since Python 3.6, so I'm sure you have heard of them by now, but you may not be aware of the full extent of their powers.

Formatting text and numbers

F-strings support Python's Format Specification Mini-Language, so you can embed a lot of formatting operations into their modifiers. It allows us to align or center text, add leading zeros/spaces, set thousands separators, and a lot more. Here are a few examples:

pi = 3.1415926
print(f'Pi is approximately equal to {pi:.2f}')
$ Pi is approximately equal to 3.14

id = 1
print(f"The id is {id:03d}")
$ The id is 001

N = 1000000000
print(f'His net worth is ${N:,d}')
$ His net worth is $1,000,000,000
text = "hello world"

# Center text:
print(f"{text:^15}")
$ ' hello world '

number = 1234567890

# Set separator
print(f"{number:,}")
$ 1,234,567,890

number = 123
# Add leading zeros
print(f"{number:08}")
$ 00000123

Nested F-Strings

If basic f-strings aren't good enough for your formatting needs you can even nest them into each other, allowing you for example to format the float and right-align the string:

number = 254.3463
print(f"{f'${number:.3f}':>10s}")
$ ' $254.346'

Date and Time Formatting

Applying number formatting with f-strings is pretty common, but did you know that you can also format dates and timestamp strings?

f-strings can format date and time as if you used datetime.strftime method. This is extra nice, when you realize that there are more formats than just the few mentioned in the docs. Python's strftime supports also all the formats supported by the underlying C implementation, which might vary by platform and that's why it's not mentioned in docs. With that said you can take advantage of these formats anyway and use for example %F, which is an equivalent of %Y-%m-%d or %T which is an equivalent of %H:%M:%S, also worth mentioning are %x and %X which are locales preferred date and time formats respectively. Usage of these formats is obviously not limited to f-strings. Refer to the Linux manpages for full list of formats.

from datetime import datetime
today = datetime.today()

print(f"{today:%Y-%m-%d}")
$ 2022-03-11

print(f"{today:%Y}")
$ 2022

print(f"Today is {today}")
$ Today is 2021-07-31 18:20:48.956829

print(f"Today is {today:%B %d, %Y}")
$ Today is July 31, 2021

print(f"Today is {today:%m-%d-%Y}")
$ Today is 07-31-2021

Proper Escaping

There are of course a few situations that will require some extra attention when handling a few characters. Here are a few examples:

name = "Paul"

print(f'My name is \'{name}\'.')
$ My name is 'Paul'.

print(f'My name is {{name}}.')
$ My name is {name}.

print(f'My name is {{{name}}}.')
$ My name is {Paul}.

print(f'My name is \\{name}\\.')
$ My name is \Paul\.

Conclusion

In addition to being easier to read than the traditional C-Style formatting such as %, or the format() method, f-strings are also optimized and much faster to process...so this is definitely a winning solution.

Posted Comments: 0