I found this python example online and I'd like to understand exactly how the number formatting works:
print "%.*g\t%.*g" % (xprecision, a, yprecision, b)
I can see by experimentation that this prints a (with precision xprecision), a tab and then b (with precision yprecision). So, as a simple example, if I run
print "%.*g\t%.*g" % (5, 2.23523523, 3, 12.353262)
then I get
2.2352 12.4
I understand how %g
usually works. I also understand how the %
generally works. What is confusing me in this example is the construct %.*g
. How does the *
work here? I can see that it is somehow taking the desired precision value and substituting it into the print expression, but why is that happening? Why does the precision number appear before the number being formatted in (xprecision, a...)?
Can someone break this down and explain it to me?
In Python, to print 2 decimal places we will use str. format() with “{:. 2f}” as string and float as a number. Call print and it will print the float with 2 decimal places.
A format of . 2f (note the f ) means to display the number with two digits after the decimal point. So the number 1 would display as 1.00 and the number 1.5555 would display as 1.56 .
The Python __format__() method implements the built-in format() function as well as the string. format() method. So, when you call format(x, spec) or string. format(spec) , Python attempts to call x.
*
is a size placeholder. It tells the formatting operation to take the next value from the right-hand-side tuple and use that as the precision instead.
In your example, the 'next' value is 5
for the first slot, so you could read this as %.5g
, which is used to format 2.23523523
. The second slot uses 3
for the width, so becomes %.3g
to format 12.353262
.
See the String Formatting Operations documenation:
A conversion specifier contains two or more characters and has the following components, which must occur in this order:
(...)
Minimum field width (optional). If specified as an
'*'
(asterisk), the actual width is read from the next element of the tuple in values, and the object to convert comes after the minimum field width and optional precision.Precision (optional), given as a
'.'
(dot) followed by the precision. If specified as'*'
(an asterisk), the actual width is read from the next element of the tuple in values, and the value to convert comes after the precision.
So both the minimum width and the precision can be made variable with *
, and the documenation explicitly states that the value to convert comes after the width and precision.
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