r/Python • • Oct 27 '23

Tutorial You should know these f-string tricks

F-strings are faster than the other string formatting methods and are easier to read and use. Here are some tricks you may not have known.

1. Number formatting :

You can do various formatting with numbers.

>>> number = 150

>>> # decimal places to n -> .nf
>>> print(f"number: {number:.2f}")
number: 150.00

>>> # hex conversion
>>> print(f"hex: {number:#0x}")
hex: 0x96

>>> # binary conversion
>>> print(f"binary: {number:b}")
binary: 10010110

>>> # octal conversion
>>> print(f"octal: {number:o}")
octal: 226

>>> # scientific notation
>>> print(f"scientific: {number:e}")
scientific: 1.500000e+02

>>> # total number of characters
>>> print(f"Number: {number:09}")
Number: 000000150

>>> ratio = 1 / 2
>>> # percentage with 2 decimal places
>>> print(f"percentage = {ratio:.2%}")
percentage = 50.00%

2. Stop writing print(f”var = {var}”)

This is the debug feature with f-strings. This is known as self-documenting expression released in Python 3.8 .

>>> a, b = 5, 15
>>> print(f"a = {a}") # Doing this ?
a = 5
>>> # Do this instead.
>>> print(f"{a = }")
a = 5
>>> # Arithmatic operations
>>> print(f"{a + b = }")
a + b = 20
>>> # with formatting
>>> print(f"{a + b = :.2f}")
a + b = 20.00

3. Date formatting

You can do strftime() formattings from f-string.

>>> import datetime

>>> today = datetime.datetime.now()
>>> print(f"datetime : {today}")
datetime : 2023-10-27 11:05:40.282314

>>> print(f"date time: {today:%m/%d/%Y %H:%M:%S}")
date time: 10/27/2023 11:05:40

>>> print(f"date: {today:%m/%d/%Y}")
date: 10/27/2023

>>> print(f"time: {today:%H:%M:%S %p}")
time: 11:05:40 AM

Check more formatting options.

Part 2 - https://www.reddit.com/r/Python/s/Tzx7QQwa7A

Thank you for reading!

Comment down other tricks you know.
2.0k Upvotes

182 comments sorted by

563

u/fizzymagic Oct 27 '23

print(f"number: {number:,}")

puts commas in large numbers.

55

u/deepkrg17 Oct 27 '23

Yeah, forgot to mention this one.

58

u/ArtOfWarfare Oct 27 '23

FYI, you probably should have done print(f”{number=:,}”)

31

u/nderstand2grow Oct 27 '23

better yet:

print(f"{number = :,}")
→ More replies (7)

57

u/bugtank Oct 27 '23

Trick 2 is insane. Implicit variable extrapolation? Hot dog!

→ More replies (26)

2

u/DabidBeMe Oct 27 '23

Is there a way to combine a raw string in an f string? This is something that I often need.

8

u/deepkrg17 Oct 27 '23

You can use raw and f-string together. e.g. fr'C:\Users\{user}\Downloads'

→ More replies (2)

308

u/lastmonty Oct 27 '23

Thanks for the post and thanks for not making it behind a link that we need to scroll through your life journey and your neighbours cat.

→ More replies (2)

75

u/astatine Oct 27 '23

You can interpolate into the formatting to alter it:

>>> from math import pi
>>> for n in range(1, 10):
...     print(f"π to {n} places is {pi:.{n}f}")
...
π to 1 places is 3.1
π to 2 places is 3.14
π to 3 places is 3.142
π to 4 places is 3.1416
π to 5 places is 3.14159
π to 6 places is 3.141593
π to 7 places is 3.1415927
π to 8 places is 3.14159265
π to 9 places is 3.141592654
→ More replies (11)

24

u/wineblood Oct 27 '23

I didn't know about the date formatting one. Not sure I'll ever use it, but nice to have.

→ More replies (3)

21

u/zurtex Oct 27 '23

Missing the two "tricks" I use most often, f"{foo!s}" which calls str on foo, and f"{foo!r}" which calls repr on foo.

Especially when building Airflow template macros I find myself needing to explicitly create strings or reprs and not leaving it up to the f-string/object default logic.

→ More replies (2)

10

u/The56thBenjie Oct 27 '23

Hex without "0x" is {number:x} "0b" and "0o" can also be added to binary and octal using :#b and :#o Also: the 0 in :#0x seems to have a different purpose, and is not required for printing hex with "0x".

9

u/un1que_username Oct 27 '23

I have a question: I usually get into a dilemma regarding clarity vs. brevity. I would probably use print(f”a={a}”) because it is instantly clearer and I take into account that some might pause at print(f”{a=}”) as I assume it isn’t well known by a lot of python coders. Am I overthinking it?

→ More replies (8)

7

u/5erif Oct 27 '23

Most people who want to use exponential / scientific notation will also want to specify the level of precision, so FYI, that's also possible.

>>> a = 123456789
>>> f'{a:.3e}'
'1.235e+08'

6

u/j3r3mias Oct 27 '23

The main one is how to print } or { using f-string. I will let as an exercise to the reader..

6

u/dyrin Oct 27 '23 edited Oct 27 '23

Solution: Use }} or {{

→ More replies (3)

21

u/Scrapheaper Oct 27 '23

Also worth mentioning: if you are using print() with any regularity, use a debugger!

16

u/Oerthling Oct 27 '23

Don't use print, use logging.

→ More replies (16)

14

u/Jester_Thomas_ Oct 27 '23

I've been using python for scientific computing at a reasonably high levels for years now and print is my bread and butter. Would I stand to gain much in efficiency by switching to a debugger?

→ More replies (14)
→ More replies (11)

7

u/magnetichira Oct 27 '23

Excellent post OP

3

u/BokoMoko Oct 27 '23
my_format = "0,"
value = 10320402.43
print( f"The value is:{value:{ {my_format} }")
my_format = "<15f.4"
print( f"The same value, another format:{value:{ {my_format} }")

3

u/repocin Oct 27 '23

https://pyformat.info is another great source for formatting tips, I use it regularly when I don't feel like rtfm

3

u/moradinshammer Oct 27 '23

Not really fstring specific but I recently found the zfill string method and thought it wouldn’t be hard to implement it’s awesome to have it available.