I now benchmarked the different approaches. is.digit()
is way faster, and depending on what you do with it (e.g., large iterations) it might be worthile using it over an own function. (And it looks prettier btw.)
I put it into a IPython notebook if you want to run it on your machine:
And here are the results if:
import timeit
def string_is_int(a_str):
try:
int(a_str)
return True
except ValueError:
return False
an_int = '123'
no_int = '123abc'
%timeit string_is_int(an_int)
%timeit string_is_int(no_int)
%timeit an_int.isdigit()
%timeit no_int.isdigit()
1000000 loops, best of 3: 401 ns per loop
100000 loops, best of 3: 3.04 µs per loop
10000000 loops, best of 3: 92.1 ns per loop
10000000 loops, best of 3: 96.3 ns per loop
Also, I have tested the more general case:
import timeit
def string_is_number(a_str):
try:
float(a_str)
return True
except ValueError:
return False
a_float = '1.234'
no_float = '123abc'
a_float.replace('.','',1).isdigit()
no_float.replace('.','',1).isdigit()
%timeit string_is_number(an_int)
%timeit string_is_number(no_int)
%timeit a_float.replace('.','',1).isdigit()
%timeit no_float.replace('.','',1).isdigit()
1000000 loops, best of 3: 400 ns per loop
1000000 loops, best of 3: 1.15 µs per loop
1000000 loops, best of 3: 452 ns per loop
1000000 loops, best of 3: 394 ns per loop