Python str() or repr() on a float?
Published 29 January 2015 under python
We often need to convert objects into their string representation for nice output. To do this in python we can use the
str() built-in function. However, it may not always be the best function to use. This is especially true if we want to accurately output a float as a string:
>>> x = 1.000000000009 >>> str(x) '1.00000000001'
From the python 2 manual:
Return a string containing a nicely printable representation of an object. For strings, this returns the string itself. The difference with repr(object) is that str(object) does not always attempt to return a string that is acceptable to eval(); its goal is to return a printable string. If no argument is given, returns the empty string, ''.
So, if we want to show a user the exact float we'll need to use
repr instead of
>>> x = 1.000000000009 >>> repr(x) '1.000000000009'
str on a tuple containing a float produces the following output:
x = (1.000000000009, 3) >>> str(x) '(1.000000000009, 3)'
It turns out that this is because printing out a tuple uses
PyObject_Print which has the following documentation:
int PyObject_Print(PyObject *o, FILE *fp, int flags)
Print an object o, on file fp. Returns -1 on error. The flags argument is used to enable certain printing options. The only option currently supported is Py_PRINT_RAW; if given, the str() of the object is written instead of the repr().
The call to
PyObject_Print within tuple's print function doesn't have the
Py_PRINT_RAW flag set and therefore, prints out the repr of each object within it. So even if you call str on the tuple you'll get its objects' repr representations, which may not be what you're expecting!