I feel a bit silly for asking what I'm sure is a rather basic question, but I've been learning Python and I'm having difficulty understanding what exactly the "g" and "G" string formats actually do.
The documentation has this to say:
Floating point format. Uses lowercase exponential format if exponent is less than -4 or not less than precision, decimal format otherwise.
I'm sure this is supposed to make sense, but I'm just not getting it. Can someone provide a clearer explanation for this format, and possibly provide some examples of when and how it should be used, vs. just using "e" or "f".
Thanks
These examples are probably illustrative:
>>> numbers = [100, 10, 1, 0.1, 0.01, 0.001, 0.0001, 0.00001]
>>> for number in numbers:
... print "%%e=%e, %%f=%f, %%g=%g" % (number, number, number)
...
%e=1.000000e+02, %f=100.000000, %g=100
%e=1.000000e+01, %f=10.000000, %g=10
%e=1.000000e+00, %f=1.000000, %g=1
%e=1.000000e-01, %f=0.100000, %g=0.1
%e=1.000000e-02, %f=0.010000, %g=0.01
%e=1.000000e-03, %f=0.001000, %g=0.001
%e=1.000000e-04, %f=0.000100, %g=0.0001
%e=1.000000e-05, %f=0.000010, %g=1e-05
>>> for number in numbers:
... print "%%0.2e=%0.2e, %%0.2f=%0.2f, %%0.2g=%0.2g" % (number, number, number)
...
%0.2e=1.00e+02, %0.2f=100.00, %0.2g=1e+02
%0.2e=1.00e+01, %0.2f=10.00, %0.2g=10
%0.2e=1.00e+00, %0.2f=1.00, %0.2g=1
%0.2e=1.00e-01, %0.2f=0.10, %0.2g=0.1
%0.2e=1.00e-02, %0.2f=0.01, %0.2g=0.01
%0.2e=1.00e-03, %0.2f=0.00, %0.2g=0.001
%0.2e=1.00e-04, %0.2f=0.00, %0.2g=0.0001
%0.2e=1.00e-05, %0.2f=0.00, %0.2g=1e-05
One of the nice things about Python is that it is easy to test something out in the interpreter when you don't understand exactly what it means.