How can I check if a string represents an int, without using try/except?

前端 未结 19 1857
悲哀的现实
悲哀的现实 2020-11-22 00:36

Is there any way to tell whether a string represents an integer (e.g., \'3\', \'-17\' but not \'3.14\' or \'asf

19条回答
  •  感情败类
    2020-11-22 01:07

    I guess the question is related with speed since the try/except has a time penalty:

     test data

    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)
    

     numpy solution (only works with arrays and unicode)

    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
    

    try/except

    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.

提交回复
热议问题