Best way to check if string is an integer?
Tim Chase
python.list at tim.thechases.com
Sat Apr 5 20:28:31 EDT 2008
> I always do it the first way. It is simpler, and should be faster.
Ditto. Using int() is best. It's clear, it's correct, and it
should be as fast as it gets.
>> if c in '0123456789':
>> print "integer"
>> else:
>> print "char"
>
> Also, the second way will only work on single-digit numbers
> (you would have to iterate over the entire string with a for
> loop to use it on numbers with more than one digit).
It also catches things like c="1234" but misses negative numbers
too. It's a bad solution on a number of levels. The isdigit()
method of a string does much of what int() does for testing "is
this an int" except that it too misses negative numbers.
-tkc
More information about the Python-list
mailing list