Is there any way to tell whether a string represents an integer (e.g., \'3\'
, \'-17\'
but not \'3.14\'
or \'asf
I guess the question is related with speed since the try/except has a time penalty:
First, I created a list of 200 strings, 100 failing strings and 100 numeric strings.
from random import shuffle
numbers = [u'+1'] * 100
nonumbers = [u'1abc'] * 100
testlist = numbers + nonumbers
shuffle(testlist)
testlist = np.array(testlist)
np.core.defchararray.isnumeric can also work with unicode strings np.core.defchararray.isnumeric(u'+12')
but it returns and array. So, it's a good solution if you have to do thousands of conversions and have missing data or non numeric data.
import numpy as np
%timeit np.core.defchararray.isnumeric(testlist)
10000 loops, best of 3: 27.9 µs per loop # 200 numbers per loop
def check_num(s):
try:
int(s)
return True
except:
return False
def check_list(l):
return [check_num(e) for e in l]
%timeit check_list(testlist)
1000 loops, best of 3: 217 µs per loop # 200 numbers per loop
Seems that numpy solution is much faster.