Can you display an integer value with leading zeroes using the str.format
function?
Example input:
"{0:some_format_specifying_width_3}".format(1) "{0:some_format_specifying_width_3}".format(10) "{0:some_format_specifying_width_3}".format(100)
Desired output:
"001" "010" "100"
I know that both zfill
and %
-based formatting (e.g. '%03d' % 5
) can accomplish this. However, I would like a solution that uses str.format
in order to keep my code clean and consistent (I'm also formatting the string with datetime attributes) and also to expand my knowledge of the Format Specification Mini-Language.
For padding a string with leading zeros, we use the zfill() method, which adds 0's at the starting point of the string to extend the size of the string to the preferred size. In short, we use the left padding method, which takes the string size as an argument and displays the string with the padded output.
The format() method of String class in Java 5 is the first choice. You just need to add "%03d" to add 3 leading zeros in an Integer. Formatting instruction to String starts with "%" and 0 is the character which is used in padding. By default left padding is used, 3 is the size and d is used to print integers.
Use the format() function to add zeros to a float after the decimal, e.g. result = format(my_float, '. 3f') . The function will format the number with exactly N digits following the decimal point.
You could just use x. split('1')[0] if performance doesn't matter. +1 This is probably the most straightforward way to deal with a string of all zeroes.
>>> "{0:0>3}".format(1) '001' >>> "{0:0>3}".format(10) '010' >>> "{0:0>3}".format(100) '100'
Explanation:
{0 : 0 > 3} │ │ │ │ │ │ │ └─ Width of 3 │ │ └─ Align Right │ └─ Fill with '0' └─ Element index
Derived from Format examples, Nesting examples in the Python docs:
>>> '{0:0{width}}'.format(5, width=3) '005'
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