Say I wanted to display the number 123 with a variable number of padded zeroes on the front.
For example, if I wanted to display it in 5 digits I would have digits = 5 giving me:
00123
If I wanted to display it in 6 digits I would have digits = 6 giving:
000123
How would I do this in Python?
Python uses C-style string formatting to create new, formatted strings. The "%" operator is used to format a set of variables enclosed in a "tuple" (a fixed size list), together with a format string, which contains normal text together with "argument specifiers", special symbols like "%s" and "%d".
When formatting the floating point number 123.4567 , we've specified the format specifier ^-09.3f . These are: ^ - It is the center alignment option that aligns the output string to the center of the remaining space. - - It is the sign option that forces only negative numbers to show the sign.
A format of . 2f (note the f ) means to display the number with two digits after the decimal point. So the number 1 would display as 1.00 and the number 1.5555 would display as 1.56 .
We can also use the round() function to fix the numbers of digits after the decimal point. This function limits the number of digits after the decimal point on the input number. It also rounds off the digit at which limit is set to its upper integral value if the digit is greater than value 5 .
If you are using it in a formatted string with the format()
method which is preferred over the older style ''%
formatting
>>> 'One hundred and twenty three with three leading zeros {0:06}.'.format(123) 'One hundred and twenty three with three leading zeros 000123.'
See
http://docs.python.org/library/stdtypes.html#str.format
http://docs.python.org/library/string.html#formatstrings
Here is an example with variable width
>>> '{num:0{width}}'.format(num=123, width=6) '000123'
You can even specify the fill char as a variable
>>> '{num:{fill}{width}}'.format(num=123, fill='0', width=6) '000123'
There is a string method called zfill:
>>> '12344'.zfill(10) 0000012344
It will pad the left side of the string with zeros to make the string length N (10 in this case).
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