Problems with conversion of values in strings to integers

Karl Scalet news at yebu.de
Mon Oct 6 08:06:52 EDT 2003


Jørgen Cederberg wrote:

> Hi,
> 
> using Python 2.2.1 on Windows and QNX I'm having trouble understandig 
> why int() raises a ValueError exception upon converting strings.
> 
>  >>> int('-10')
> -10
>  >>> int('10')
> 10
>  >>> int(10.1)
> 10
>  >>> int('10.1')
> Traceback (most recent call last):
>   File "<stdin>", line 1, in ?
> ValueError: invalid literal for int(): 10.1
> 
> This is quite frustating. The only solution I can see is to do:
>  >>> int(float('10.1'))
> 10

depending on what you actually want,
 >>> int(round('10.1'))
might be appropriate.
But if you really want the "floor"-value,
nothing is wrong with your approach.

Karl





More information about the Python-list mailing list