string.atoi and string.atol broken?

Steven Bethard steven.bethard at gmail.com
Tue Jan 25 18:50:28 EST 2005


Mike Moum wrote:
>>>>> s.atoi('4',3)
>>
>> Traceback (most recent call last):
>>   File "<pyshell#2>", line 1, in -toplevel-
>>     s.atoi('4',3)
>>   File "/usr/lib/python2.3/string.py", line 220, in atoi
>>     return _int(s, base)
>> ValueError: invalid literal for int(): 4

What did you expect the value of '4' in base 3 to be?  There is no '4' 
in base 3... only '0', '1' and '2'.

>>>>> s.atoi('8',4)
>>
>> Traceback (most recent call last):
>>   File "<pyshell#6>", line 1, in -toplevel-
>>     s.atoi('8',4)
>>   File "/usr/lib/python2.3/string.py", line 220, in atoi
>>     return _int(s, base)
>> ValueError: invalid literal for int(): 8

And no '8' in base 3 either.


> Is this a bug, or am I missing something obvious?

Well, first of all, unless you're using a Python before 2.0, you're 
missing that string.atoi is deprecated.  You should be using int(), 
which can take the same parameters.

I think secondly, you're missing that int(string, base) converts the 
given string to an int assuming that the string is in the given base. 
If the numbers you provide are out of the range of the digits that are 
valid for that base, you will get an error.

Steve



More information about the Python-list mailing list