[Tutor] rep() and str(0

Danny Yoo dyoo@hkn.eecs.berkeley.edu
Sun, 30 Jun 2002 11:53:36 -0700 (PDT)


On Sun, 30 Jun 2002, Thomas Rivas wrote:

> >>>str(4.53-2j)
> '(4.53-2j)'
> >>>
> >>>str(1)
> '1'
> >>>
> >>>str(2e10)
> '20000000000.0'
> >>>
> >>>repr([0, 5, 9, 9])
> '[0, 5, 9, 9]'
> >>>
> >>>`[0, 5, 9, 9]`
> '[0, 5, 9, 9]'
>
> In my experience all three usually return the exact same string.


Here's one place where repr() and str() return different kinds of strings:

###
>>> x = 1 - .1
>>> print str(x)
0.9
>>> print repr(x)
0.90000000000000002
###

Since repr() is meant to be more "truthful" than str(), it shows us that
floating point can't hold this value precisely.

We can see another small difference when we do str() and repr() on
strings:

###
>>> story = """Mars was empty before we came.
... That's not to say that nothing had ever happened."""
>>> print repr(story)
"Mars was empty before we came.\nThat's not to say that nothing had ever
happened."
>>> print str(story)
Mars was empty before we came.
That's not to say that nothing had ever happened.
###



Hope this helps!