Best way to format integer as string with leading zeros? [duplicate]
Solution 1:
You can use the zfill()
method to pad a string with zeros:
In [3]: str(1).zfill(2)
Out[3]: '01'
Solution 2:
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
Solution 3:
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.
Solution 4:
You most likely just need to format your integer:
'%0*d' % (fill, your_int)
For example,
>>> '%0*d' % (3, 4)
'004'
Solution 5:
Python 2.6 allows this:
add_nulls = lambda number, zero_count : "{0:0{1}d}".format(number, zero_count)
>>>add_nulls(2,3)
'002'