Best way to format integer as string with leading zeros?

The standard way is to use format string modifiers. These format string methods are available in most programming languages (via the sprintf function in c for example) and are a handy tool to know about.

To output a string of length 5:


... in Python 3.5 and above: f-strings.

i = random.randint(0, 99999)
print(f'{i:05d}')

Search for f-strings here for more details.


... Python 2.6 and above:

print '{0:05d}'.format(i)

... before Python 2.6:

print "%05d" % i

See: https://docs.python.org/3/library/string.html


You can use the zfill() method to pad a string with zeros:

In [3]: str(1).zfill(2)
Out[3]: '01'

Python 3.6 f-strings allows us to add leading zeros easily:

number = 5
print(f' now we have leading zeros in {number:02d}')

Have a look at this good post about this feature.


You most likely just need to format your integer:

'%0*d' % (fill, your_int)

For example,

>>> '%0*d' % (3, 4)
'004'