How to check if a string "is" an int?

Steven D'Aprano steve at REMOVETHIScyber.com.au
Wed Dec 21 07:14:33 EST 2005


On Wed, 21 Dec 2005 03:37:27 -0800, Neuruss wrote:

> Can't we just check if the string has digits?

Why would you want to?


> For example:
> 
>>>> x = '15'
>>>> if x.isdigit():
> 	print int(x)*3

15 is not a digit. 1 is a digit. 5 is a digit. Putting them together to
make 15 is not a digit.


If you really wanted to waste CPU cycles, you could do this:

s = "1579"
for c in s:
    if not c.isdigit():
        print "Not an integer string"
        break
else:
    # if we get here, we didn't break
    print "Integer %d" % int(s)


but notice that this is wasteful: first you walk the string, checking each
character, and then the int() function has to walk the string again,
checking each character for the second time.

It is also buggy: try s = "-1579" and it will wrongly claim that s is not
an integer when it is. So now you have to waste more time, and more CPU
cycles, writing a more complicated function to check if the string can be
converted.


-- 
Steven.




More information about the Python-list mailing list