Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python number print formatting using %.*g

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?

like image 308
EPH Avatar asked Feb 12 '16 17:02

EPH


People also ask

How do I print .2f in Python?

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.

What does .2f mean in Python?

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 .

What is __ format __ in Python?

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.


1 Answers

* 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:

(...)

  1. 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.

  2. 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.

like image 168
Martijn Pieters Avatar answered Sep 30 '22 13:09

Martijn Pieters