string zero padding
You can use the zfill() function to fill a string with zeros
>>> str = "123"
>>> print(str.zfill(8))
00000123
You can also convert integers to characters to fill with zeros using zfill()
>>> num = 123
>>> print(str(num).zfill(8))
00000123
Numeric zero padding
For numbers, you can use formatting to pad zeros:
>>> number = 123
>>> zfnumber = "%08d" % number
>>> print(zfnumber)
00000123
>>> type(zfnumber)
<class 'str'>
You can see that the formatted number type becomes a character type. There are some numbers with different digits for python to fill in the front of the output integer, such as 1, 22, 333, 4444. Normally, the output as a number or converted to a string may have different digits. Sometimes the output to the text will bring in subsequent processing
.
trouble. If you want to ensure the same number of digits, add 0 in front.
The operation is very simple, just use s = '%04d' % n to convert it into a string.
give a chestnut
for n in range(1000):
s = '%04d' % n
print(s)
One of the small problems is that if the 0 in %04d is missing, there will be problems when it is written as %4d.