Leading zeros in Python

JANUARY 27, 2023

Leading zeros are extra zeros to the left of a number when you want to have a regular amount of digits in a set of numbers. For instance, 0001, 0002, and 0003 is a good formatting if you think you'll get to have thousands of entries, as you can stay at four digits up to 9999.

# Define your number
number = 1

two_digits = f'{number:02d}'
# 01

four_digits = f'{number:04d}'
# 0001

We use the Python formatting helper {my_number:04d} to enforce a minimum set of digits in our number variable. This means you can use it to set the value of a string or to create or print a longer string with that number, not necessarily having to store its value.

a_number = 42
print(f'The number is {a_number:06d}.')
# The number is 000042.

print(f'The number is {512:06d}.')
# The number is 000512.