int('2.1') does not work while int(float('2.1')) does

Erik Max Francis max at alcyone.com
Mon Apr 5 23:34:45 EDT 2004


Vineet Jain wrote:

> int('2.1') does not work while int(float('2.1')) does. If int can
> covert a
> float object then there is no reason why a float string should not be
> converted too.
> 
> When I do int('2.1') I get the following error:
> 
> >>> a = int('2.0')
> Traceback (most recent call last):
>   File "<stdin>", line 1, in ?
> ValueError: invalid literal for int(): 2.0
> 
> This does not seem very pythonic

There's a fundamental difference between an int and a float.  If the
string you're trying to convert looks like a float, that means it
doesn't look like an int.

With your first example of '2.1', what should it mean?  Should it
truncate, round to negative infinity round to positive infinity, round
to zero, what?  Python can't guess for you, so it shouldn't try.  Thus
it's an error.

-- 
 __ Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/
/  \ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis
\__/ If I had another face, do you think I'd wear this one?
    -- Abraham Lincoln



More information about the Python-list mailing list