printing anomaly

Greg Ewing greg at cosc.canterbury.ac.nz
Mon Mar 21 06:32:20 CET 2005


Paul Rubin wrote:
> What's the deal with this?
> 
>     >>> print 3.2
>     3.2
>     >>> print [3.2]
>     [3.2000000000000002]
>     >>> 
> 
> Yes, I know that 3.2 isn't an exact binary fraction.  I'm wondering
> why it's converted differently depending on whether it's in a list.

It's not. The difference is that print uses str() to convert
its arguments to strings, whereas lists always use repr()
to convert their elements to strings, regardless of whether
you use str() or repr() on the list as a whole.

A simple experiment shows the difference between str()
and repr() on floats:

Python 2.3.4 (#1, Jun 30 2004, 16:47:37)
[GCC 3.2 20020903 (Red Hat Linux 8.0 3.2-7)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
 >>> str(3.2)
'3.2'
 >>> repr(3.2)
'3.2000000000000002'

-- 
Greg Ewing, Computer Science Dept,
University of Canterbury,	
Christchurch, New Zealand
http://www.cosc.canterbury.ac.nz/~greg



More information about the Python-list mailing list