3 Python Tricks That Will Improve Your Code

3 Python Tricks That Will Improve Your Code

I decided to do a bit of research about Python improvements. Those 3.6, 3.7, 3.8 Python versions aren’t there for nothing, right? After going through release notes, I found these neat tricks that I would like to share with you.

By reading this article, you’ll learn:

  • How to format big integers more clearly

  • A better way to work with file paths

  • The proper way of string formating

1. Formatting big integers


From Python 3.6 (and onwards) you can use underscores to make numbers easier to read. See PEP 515 for more details.

Let’s look at an example:

  a = 1000000000 
 # Is variable a billion or 100 millions?
 # Let's use underscores to make it easier to read
 a = 1_000_000_000
  # You can group numbers as you like
 b = 1_0_9_0 

It also works with hexadecimal addresses and grouping bits.

# grouping hexadecimal addresses by words
addr = 0xCAFE_F00D
# grouping bits into nibbles in a binary literal
 flags = 0b_0011_1111_0100_1110

2. Pathlib


Working with paths can be challenging especially if your code needs to run on multiple operating systems.

Luckily for us, Python standard library has pathllib.

Let’s look at an example:

from pathlib import Path
path = Path("some_folder")
# output: some_folder
# We can add more subfolders in a readable way
path = path / "sub_folter" / "sub_sub_folder"
# output: some_folder/sub_folter/sub_sub_folder
# make path absolute
# output: /Users/r.orac/some_folder/sub_folter/sub_sub_folder

3. Simplify string formatting


I’m used to using old school string formatting in Python:

person = 'Roman'
exercise = 0
print("%d-times %s exercised during corona epidemic" % (exercise, person))
# output
# 0-times Roman exercised during corona epidemic

Until recently, I didn’t know there is a better (more modern) way of string formatting in Python.

In Python 3.6, PEP 498 introduces Literal String Interpolation, which simplifies the string formatting.

We can rewrite the example above to:

person = 'roman'
exercise = 0
print(f"{exercise}-times {person} exercised during corona epidemic")
# output
# 0-times Roman exercised during corona epidemic

A string prefixed with f is known as fstring.

fstrings even support math operations:

print(f"{exercise+1}-times {person} exercised during corona epidemic")
# Output
# '1-times roman exercised during corona epidemic' 

But I didn’t exercise during the corona epidemic so adding +1 in the fstring would simply be a lie 😂

What about formatting float values?

f = 0.333333
print(f"this is f={f:.2f} rounded to 2 decimals")
# Output
this is f=0.33 rounded to 2 decimals


These Python tricks will make your code more concise and will make coding more enjoyable.

Many Python developers don’t know about these tricks — you’re not one of them anymore.

Before you go

Join me on TELEGRAM, where I regularly post about Web dev and Ethical hacking.