I’m trying to use string.format on a ‘nan’ float.
Here’s the description of the ‘g’ option from the python documentation.
General format. This prints the number as a fixed-point number, unless the number is too large, in which case it switches to ‘e’ exponent notation. Infinity and NaN values are formatted as inf, -inf and nan, respectively.
And here’s what i get trying it in the 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 bug or am I doing it wrong?
repr(float)was fixed in Python 2.6 and Python 3.0; see http://bugs.python.org/issue1635; howeverstr.formatwas not fixed until the 2.7 branch; see http://hg.python.org/cpython/rev/c5e0d9beebf9 and http://bugs.python.org/issue1580.I’d recommend seeing if
"{0!r}"works for you; that should call into the non-brokenreprcode.If you need to use
"{0:g}"format spec, you could try subclassingfloatand overriding__format__: