To pad an integer with leading zeros to a specific length To display the integer as a decimal value, call its ToString(String) method, and pass the string "Dn" as the value of the format parameter, where n represents the minimum length of the string.
When leading zeros occupy the most significant digits of an integer, they could be left blank or omitted for the same numeric value. Therefore, the usual decimal notation of integers does not use leading zeros except for the zero itself, which would be denoted as an empty string otherwise.
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 = 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'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With