How can I format a float with a given precision and zero padding?

I looked at dozens of similar questions - and I'm glad to just get a link to another answer, but I want a floating point zero in python 3.3

n = 2.02 print( "{?????}".format(n)) # desired output: 002.0200 

The accuracy of the float is simple, but I also can't get a zero padding. What is included in <? P>

+5
source share
2 answers

You can use format specifiers like

 >>> "{:0>8.4f}".format(2.02) '002.0200' >>> print("{:0>8.4f}".format(2.02)) 002.0200 >>> 

Here 8 represents the total width, .4 represents the accuracy. And 0> means the line should be right justified and filled to the left of 0 .

+7
source

You can do this using both the old and the new formatting method for strings:

 In [9]: "%08.4f" %(2.02) Out[9]: '002.0200' In [10]: "{:08.4f}".format(2.02) Out[10]: '002.0200' 
+1
source

Source: https://habr.com/ru/post/1214626/


All Articles