repr/str diff between Python 2 and 3

Ben Finney ben+python at benfinney.id.au
Tue Oct 11 21:17:04 EDT 2016


Skip Montanaro <skip.montanaro at gmail.com> writes:

> >>> print repr(27.04 - 0.01)
> 27.029999999999998
> >>> print str(27.04 - 0.01)
> 27.03
>
> My test case writes through a csv writer, which writes the str() of each
> element to the output.

For Python 2, that's a mistake:

    str(object='')

    Return a string containing a nicely printable representation of an
    object. […] 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. […]

    <URL:https://docs.python.org/2/library/functions.html#str>

So, for preserving the value, you don't want ‘str(obj)’. That's what
‘repr(obj)’ is for:

    repr(object)

    Return a string containing a printable representation of an object.
    […] For many types, this function makes an attempt to return a
    string that would yield an object with the same value when passed to
    eval() […]

    <URL:https://docs.python.org/2/library/functions.html#repr>

> Is there documentation of this particular change? My searching turned
> up documentation of plenty of other changes, but not this particular
> one.

Only that one should not rely on ‘str’ preserving the value accurately,
as documented in Python 2.

-- 
 \      “[Entrenched media corporations will] maintain the status quo, |
  `\       or die trying. Either is better than actually WORKING for a |
_o__)                  living.” —ringsnake.livejournal.com, 2007-11-12 |
Ben Finney




More information about the Python-list mailing list