Python nanostream formatting

I am trying to use string.format on the planet 'nan'.

Here's a description of the 'g' option from the python documentation .

General format. This number is printed as a fixed point number if the number is not too large, in which case it switches to the "e" exponent. Infinity and NaN values ​​are formatted as inf, -inf, and nan, respectively.

And here is what I am trying to use in an interpreter (Python 2.6):

>>> print "{0:g}".format(float('nan'))
-1.#IND

As I understand the documentation, the output should be "nan."

Is this a mistake or am I doing it wrong?

+5
source share
1 answer

repr(float) Python 2.6 Python 3.0; . http://bugs.python.org/issue1635; str.format 2.7; . http://hg.python.org/cpython/rev/c5e0d9beebf9 http://bugs.python.org/issue1580.

, "{0!r}" ; repr.

"{0:g}", float __format__:

class FixFloat(float):
    def __format__(self, format_spec):
        return 'nan' if math.isnan(self) else float.__format__(self, format_spec)

"{0:g}".format(FixFloat(1.2345e9))
'1.2345e+09'
"{0:g}".format(FixFloat(float('nan')))
'nan'
+7