Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python add leading zeroes using str.format [duplicate]

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.

like image 920
butch Avatar asked Jun 14 '13 22:06

butch


People also ask

How do you add leading zeros to a string in Python?

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.

How do you add leading zeros to a string?

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.

How do I add a zero after a number in Python?

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.

How do you find the leading zeros in Python?

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.


2 Answers

>>> "{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 
like image 92
Andrew Clark Avatar answered Oct 01 '22 09:10

Andrew Clark


Derived from Format examples, Nesting examples in the Python docs:

>>> '{0:0{width}}'.format(5, width=3) '005' 
like image 38
msw Avatar answered Oct 01 '22 10:10

msw