ValueError: invalid literal for int(): 1.0000000000e+00

Terry Reedy tjreedy at udel.edu
Tue Feb 15 00:37:24 EST 2005


"Fredrik Lundh" <fredrik at pythonware.com> wrote in message 
news:cuqp0k$h80$1 at sea.gmane.org...
> Terry Reedy wrote:
>> int(somestring) without a radix argument requires that somestring be an 
>> decimal integer literal and nothing more and nothing else.
>
> but specifying a radix won't help you, though:

My statement as intended to be read, in its totality, is exactly true. 
Remove 'without a radix argument', which is the case under discussion, and 
it becomes false unless 'decimal' is also removed.  But then one must 
specify that the radix match the literal.  If somestring is a non-decimal 
integer literal (something else), then radix is necessary, and not just 
helpful, for correct execution.

>>> int('033')
33
>>> int('033', 8)
27

>>> int('1a3')
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
ValueError: invalid literal for int(): 1a3
>>> int('1a3',16)
419

>>> int('4',3)
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
ValueError: invalid literal for int(): 4

I presume you know this.  I also would have thought that you would know 
better than to think that I am so ignorant and foolish as to think that 
explicitly giving a default parameter value (which is a no-op of no effect) 
would somehow magically fix an invalid input.

The essential point of my post was to clarify for the OP that the reason 
int(1.0) does not work is not because 1.0 is a float literal (which is 
irrelevant to int) but because it is something more (and not 'nothing 
more') than a decimal integer literal.  And so I gave the additional 
example of int(1x) not working.

Knowing that int stops scanning at the first invalid-for-the-radix 'digit' 
explains why it cannot autoconvert a string whose unseen continuation makes 
it float literal.  If one mistakingly assumes that int uses the same lexer 
as Python itself, then one will mistakenly conclude the int will be 
informed that the string constitutes a float literal.  If this were true, 
then expecting the int of the corresponding float value would be 
reasonable.

Even when people know that scanning stops, they often are surprised by the 
exception being raised.  (Indeed, the design could have been otherwise.) 
Clp periodically gets posts like "My string s equal to '123abc' starts with 
a valid decimal integer literal, so why does int(s) fail?" and "You mean I 
really have slice the int away from the rest?"  So I thought it worthwhile 
to reiterate 'nothing more'.

Terry J.Reedy






More information about the Python-list mailing list