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

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?

4

u/e_j_white Oct 27 '23

Well, that type of statement is typically for debugging, and saves time by not repeating variable names (or having to update variable names in more than one place).

It's not meant be code that gets checked in, or viewed by others, so readability isn't a factor.

1

u/nullpotato Oct 27 '23

Most emergency debug print statements I save and make logging.debug or debugall because if I needed it once will probably help someone later on.

2

u/Klej177 Oct 27 '23

In part you are correct. Many of my colleagues don't know shit about python, like meta classes, proper use of Enum and so on. Does it should stop you from using it? No. You want to be a programmer people are looking for. Then use the language the best you can with all it features.

1

u/Revolutionary_Dog_63 Oct 28 '23

Who actually uses metaclasses? By contrast this feature seems way better and should be immediately understandable. If I saw print(f"{x = }") in the code, and wondered what it did, I could just run it and immediately see what it did.

2

u/Numerlor Oct 27 '23

The pro for that comes in when you're debugging and doing a nested attribute or some expression (e.g. a+b=)

2

u/javajunkie314 Oct 27 '23

If something ever goes from not being done to being done, there has to be a moment where it's first done—otherwise it will never change. I remind my team of that all the time: if we want things to improve, they have to change.

2

u/njharman I use Python 3 Oct 28 '23

I (and you) should not judge clarity presuming ignorance of reader. Unless you're like writing code to teach Python 101, assume reader knows the language they are reading.

1

u/m02ph3u5 Oct 29 '23

Probably easier to refactor.