Check if a string contains a number

后端 未结 16 1366
無奈伤痛
無奈伤痛 2020-11-22 11:14

Most of the questions I\'ve found are biased on the fact they\'re looking for letters in their numbers, whereas I\'m looking for numbers in what I\'d like to be a numberless

16条回答
  •  感情败类
    2020-11-22 12:05

    https://docs.python.org/2/library/re.html

    You should better use regular expression. It's much faster.

    import re
    
    def f1(string):
        return any(i.isdigit() for i in string)
    
    
    def f2(string):
        return re.search('\d', string)
    
    
    # if you compile the regex string first, it's even faster
    RE_D = re.compile('\d')
    def f3(string):
        return RE_D.search(string)
    
    # Output from iPython
    # In [18]: %timeit  f1('assdfgag123')
    # 1000000 loops, best of 3: 1.18 µs per loop
    
    # In [19]: %timeit  f2('assdfgag123')
    # 1000000 loops, best of 3: 923 ns per loop
    
    # In [20]: %timeit  f3('assdfgag123')
    # 1000000 loops, best of 3: 384 ns per loop
    

提交回复
热议问题