The method of filling zeros in Python numbers / strings
This article introduces the relevant knowledge of "Python digital / string zero filling method". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!
Sometimes when using Python, you want to zero a number or string, that is, to change "1" into an eight-digit "00000001". You can use the following method to fill zeros.
String zero padding:
You can use the zfill () function to add zeros to a string:
> str = "123" > print (str.zfill (8)) 00000123
You can also convert integers to characters to use zfill () to fill zeros:
> num = 123 > print (str (num) .zfill (8)) 00000123 numeric zero padding:
Zeros can be filled in a formatted way for numbers:
> number = 123 > zfnumber = "d"% number > print (zfnumber) 00000123 > type (zfnumber)
You can see that the formatted number type becomes a character type.
Python adds zeros to the output integer
There are some different digits of numbers, such as 1,22,333, 4444, which may be different as normal output as a number or a transferred string, and sometimes the output to text will cause trouble in subsequent processing. If you want to keep the number of digits the same, add 0 in front of it.
The operation is very simple, just convert it to a string with s = "d"% n.
Take a chestnut.
For n in range (1000): s = "d"% n print (s)
One small problem is that if the zero in d is missing, there will be a problem if it is written as% 4d.
This is the end of the introduction of "the method of filling zeros in Python numbers / strings". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!