Can anyone explain this behaviour?

Erik Max Francis max at alcyone.com
Sat Aug 17 00:46:20 CEST 2002


Margarida Conde wrote:

> I was just starting to learn and use python when I've found this thing
> I
> can't understand. The code follows:
> 
> from string import *
> 
> def tolist(line):
>         return(map(float, split(line)))
> 
> print(tolist('0.1'))
> print(float('0.1'))
> 
> Why do I get different results instead of:
> [0.1]
> 0.1
> ?

It's the difference between str and repr:

	print str(0.1)
	print repr(0.1)

The reason for the discrepancy is that repr prints all available digits,
whereas str rounds to make things prettier.  (I'm presuming you know why
the float representation for 0.1 is not exactly 0.1; that's simply due
to the limitations of floating point and is even mentioned in the Python
tutorial.)

Converting a builtin sequence such as a list or tuple to a string
converts each of its elements via repr, not str, regardless of whether
you converted the sequence itself with str or repr:

	print str(['a'])
	print repr(['a'])

-- 
 Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/
 __ San Jose, CA, US / 37 20 N 121 53 W / ICQ16063900 / &tSftDotIotE
/  \ There is nothing so subject to the inconstancy of fortune as war.
\__/ Miguel de Cervantes
    Church / http://www.alcyone.com/pyos/church/
 A lambda calculus explorer in Python.



More information about the Python-list mailing list