Theo van der Sluijs
Jul 23 · 2 min read

Leading zeros in a python number is not very difficult. A leading zero is any 0 digit that comes before the first nonzero digit in a number string in positional notation. For example, James Bond’s famous identifier, 007, has two leading zeros. When leading zeros occupy the most significant digits of an integer, they could be left blank or omitted for the same numeric value.

Now the sollution in python is not very difficult.

Basically what you want is numbers to be the same length like this:

001
002
003
004
010
015
045
099
100
112
156

To get leading zero’s in Python 2 you can do:

number = 1
print "%02d" % (number,)

Basically % is like printf or sprintf. Where the 2 stands for 1 leading zero, when the number is not higher then 9.

outcome: 01

Now with another number and more leading zero’s.

number = 23
print "%04d" % (number,)

outcome: 0023

To get leading zero’s in Python 3.+ the same behavior can be achieved with:

number = 6
print("{:02d}".format(number))

outcome: 06

And to get leading zero’s in Python 3.6+ the same behavior can be achieved with f-strings:

number = 4
print(f"{number:02d}")

outcome: 04

Another way of doing it is.

number = 23
print('{0:04}'.format(number))

outcome: 0023

As you can see there are multiple ways to put leading zero’s in front of a number.

purepython

Scribbles of code in Python. A new Medium publication about Python coding and other Tech.

Theo van der Sluijs

Written by

Nerd Herder ☆ Scrum Master ☆ Disruptor ☆ Python Lover (Code & Efteling) ☆ Dad ☆ Husband ☆ Zookeeper ☆ CycloCross biker ☆ Blogger ☆ Dutch

purepython

Scribbles of code in Python. A new Medium publication about Python coding and other Tech.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade