Reputation: 8098
I am reading the wrox Beginning Python book. In chapter 2, the example states
>>> print "$.03f" & 30.00123
$30.001
However this does not explain the behavior of the command. Why use .03 when .3 and .003 etc have the same behavior in the shell? Furthermore, it does not explain what happends 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 searching but couldnt get results as I dont know what the relevant keywords are.
Upvotes: 4
Views: 7008
Reputation:
I don't think "%.3f", "%.03f", and "%0.003f" have any difference among them, the number after the decimal-point is processed as a number by printf-family, so 3 == 03 == 003. However, "%.0f" will truncate the decimal places. Also, "%.f" is different from "%f".
But the representation of "03" isn't useless in printf-family, it pads zero in front of the number to be printed if necessary,
>>> print "%5d" % (123)
123
>>> print "%05d" % (123)
00123
>>> print "%5d" % (123456)
123456
"%3f" in your example does same thing as "%5d" in mine. It prints a at-least-three-number-long string. So,
>>> 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
Don't forget if the decimal point is omitted in the format string, the default decimal place is 6.
Upvotes: 1
Reputation: 9051
The 0
in '%.03f'
does nothing. This is equivalent to '%.3f'
.
As for the second question, what does '%3f'
do, it simply specifies the length for the whole number, exactly as it would in '%3s'
. It becomes clear if you make it longer:
>>> '%10f' % 2.3
' 2.300000'
>>> len(_)
10
>>>
Upvotes: 4
Reputation: 400700
This is a feature known as string formatting or string interpolation. Its documentation can be found here. It works very similarly to the C function printf
's format strings.
Upvotes: 1