Display number with leading zeros Display number with leading zeros python python

Display number with leading zeros


In Python 2 (and Python 3) you can do:

print "%02d" % (1,)

Basically % is like printf or sprintf (see docs).


For Python 3.+, the same behavior can also be achieved with format:

print("{:02d}".format(1))

For Python 3.6+ the same behavior can be achieved with f-strings:

print(f"{1:02d}")


You can use str.zfill:

print(str(1).zfill(2))print(str(10).zfill(2))print(str(100).zfill(2))

prints:

0110100


In Python 2.6+ and 3.0+, you would use the format() string method:

for i in (1, 10, 100):    print('{num:02d}'.format(num=i))

or using the built-in (for a single number):

print(format(i, '02d'))

See the PEP-3101 documentation for the new formatting functions.


matomo