Best way to format integer as string with leading zeros? [duplicate] Best way to format integer as string with leading zeros? [duplicate] python python

Best way to format integer as string with leading zeros? [duplicate]


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

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


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:

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

... 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


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

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

Have a look at this good post about this feature.