Can anyone explain this behaviour?

Steve Holden sholden at holdenweb.com
Sun Aug 18 11:01:44 EDT 2002


"Erik Max Francis" <max at alcyone.com> wrote...
> 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)))
> >
split(line) gives you a list of the whitespace-separated items in line. You
can avoid the need to import the string module by using the string method
instead:

        return map(float, line.split())

Will give you the same thing. You then map float() to each item, so your
function returns a list of floating-point numbers, one for each
whitespace-separated item in the line.

> > print(tolist('0.1'))
> > print(float('0.1'))
> >
Note that print is a statement, not a funciton, so it's eacier to write

    print tolist('0.1')
    print float('0.1')

The same is true of return.

> > 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'])
>
It can be confusing that the repr() function is used to formulate the
strings used in creating the str() of an object. Max has explained that the
two use different rules for representing numerical approximations.

regards
-----------------------------------------------------------------------
Steve Holden                                 http://www.holdenweb.com/
Python Web Programming                http://pydish.holdenweb.com/pwp/
-----------------------------------------------------------------------








More information about the Python-list mailing list