Decimal range display in python

I am reading a wrox Beginning Python book. In chapter 2, an example contains

>>> print "$.03f" & 30.00123 $30.001 

However, this does not explain the behavior of the team. Why use .03 when .3 and .003 etc. Have the same shell behavior? Also, he does not explain what happens when I just use 3

 >>> print "%.03f" % (2.34567891) 2.346 >>> print "%.003f" % (2.34567891) 2.346 >>> print "%.0003f" % (2.34567891) 2.346 >>> print "%.3f" % (2.34567891) 2.346 >>> print "%3f" % (2.34567891) 2.345679 

I tried to search, but could not get the results, because I don’t know what the relevant keywords are.

+4
source share
3 answers

0 in '%.03f' does nothing. This is equivalent to '%.3f' .

Regarding the second question, what does '%3f' , it just determines the length for the whole number, just like in '%3s' . It becomes clear if you do it longer:

 >>> '%10f' % 2.3 ' 2.300000' >>> len(_) 10 >>> 
+4
source

This is a feature known as string formatting or string interpolation. Its documentation can be found here . It is very similar to printf string strings.

+1
source

I don’t think that "% .3f", "% .03f" and "% 0.003f" have any difference between them, the number after the decimal point is treated as a number using the printf-family, so 3 == 03 == 003. However, "% .0f" truncates decimal places. In addition, "% .f" is different from "% f".

But the view "03" is not useless in printf-family, it fills in a zero before the number to be printed, if necessary,

 >>> print "%5d" % (123) 123 >>> print "%05d" % (123) 00123 >>> print "%5d" % (123456) 123456 

"% 3f" in your example does the same as "% 5d" in mine. It prints a string with a length of at least three digits. In this way,

 >>> print "%3f" % (2.34567891) 2.345679 >>> print "%3.f" % (2.34567891) 2 >>> print "%3.1f" % (2.34567891) 2.3 >>> print "%3.2f" % (2.34567891) 2.35 >>> print "%3.3f" % (2.34567891) 2.346 >>> print "%30f" % (2.34567891) 2.345679 >>> print "%30.8f" % (2.34567891) 2.34567891 >>> print "%30.9f" % (2.34567891) 2.345678910 

Remember, if the decimal point is omitted from the format string, the default decimal place is 6 ..

+1
source

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


All Articles