Leading zeros in Python

Create leading zeros with this Python script and Example. Leading zero's at the beginning of files is handy for sorting, this script will help you.

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.

>Zeros attached to the beginning of a number in this way are called leading zeros.

Now the solution in python is not very difficult.

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

001002003004010015045099100112156

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

number = 1print "%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 = 23print "%04d" % (number,)

outcome: 0023

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

number = 6print("{: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 = 4print(f"{number:02d}")

outcome: 04

Another way of doing it is.

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

outcome: 0023

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

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.

Did you find this article valuable?

Support Theo van der Sluijs by becoming a sponsor. Any amount is appreciated!