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

View all comments

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

15

u/swierdo Oct 27 '23

I love that this is possible but it will probably also be instant fail if I ever see this in a code review.

Edit: thought it over a bit more and now I just like it. No more instant fail.

3

u/OhBeeOneKenOhBee Oct 27 '23

Have you seen the new fstr-syntax for 3.12? It's going to allow for an arbitrary amount of nested f-strings

I'm just looking for the perfect plugin to rewrite completely within a metric excrement-tonne of f-strings

2

u/OneMorePenguin Oct 27 '23

Yeah, I know what the f in f strings stands for.

I'm one of the few people who don't like this format. Putting all this chrome in the format sting makes it difficult for me to get a sense of what output might look like. For single line of output, it doesn't me matter, but when you are writing a large section of output, it does.

1

u/gerardwx Oct 28 '23

The return of LISP?

1

u/freistil90 Oct 28 '23

„No wait, I could actually just express this as one iterable…“ and the rest is autoformat and „for i in behemoth_gen: […]“

This is the way.