Sometimes when using Python, you want to zero out a number or string, i.e., turn a 1 into an eight-digit 00000001, and you can use the following methods to zero out a number or string.
String complementary zero:
You can use the zfill() function to fill a string with zeros:
>>> str = "123" >>> print((8)) 00000123
It is also possible to convert an integer to a character to make up zeros using zfill().
>>> num = 123 >>> print(str(num).zfill(8)) 00000123
Numbers make up the zeros:
Numbers can be formatted to make up zeros:
>>> number = 123 >>> zfnumber = "%08d" % number >>> print(zfnumber) 00000123 >>> type(zfnumber) <class 'str'>
You can see that the formatted numeric type changes to a character type.
python prepends zeros to the output integer.
There are a number of different digits of the number, such as 1, 22, 333, 4444, the normal output as a number or a string may not be the same number of digits, some of the time the output to the text in the subsequent processing will bring trouble. If you want to ensure that the same number of digits, in front of the complement 0.
The operation is very simple, just use s = '%04d' % n to convert to a string.
give me an example
for n in range(1000): s = '%04d' % n print(s)
One of the very small problems is that if the 0 in %04d is left out, there is a problem with writing it as %4d.
summarize
This article on the Python digital/string zero operation is introduced to this article, more related Python zero operation content please search for my previous articles or continue to browse the following related articles I hope that you will support me in the future more!