Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In laymans terms, what does the Python string format "g" actually mean?

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

like image 376
user1015937 Avatar asked Nov 26 '11 22:11

user1015937


2 Answers

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.

like image 164
Michael Hoffman Avatar answered Sep 29 '22 05:09

Michael Hoffman


g and G are similar to the output you would get on a calculator display if the output is very large or very small you will get a response in scientific notation. For example 0.000001 gives "1e-06" with g and "1E-06" with G. However numbers that are not too small or too large are displayed simply as decimals 1000 gives "1000"

e always gives the result in exponential format 1000 gives 1.000000e+03

f always gives the result in decimal format, however it does not do the rounding off that g and G do 1000 gives "1000.000000"

like image 42
Andrew Marsh Avatar answered Sep 29 '22 04:09

Andrew Marsh