Check if a string contains a number

后端 未结 16 1362
無奈伤痛
無奈伤痛 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:01

    You can use range with count to check how many times a number appears in the string by checking it against the range:

    def count_digit(a):
        sum = 0
        for i in range(10):
            sum += a.count(str(i))
        return sum
    
    ans = count_digit("apple3rh5")
    print(ans)
    
    #This print 2
    
    0 讨论(0)
  • 2020-11-22 12:04

    You can use any function, with the str.isdigit function, like this

    >>> def hasNumbers(inputString):
    ...     return any(char.isdigit() for char in inputString)
    ... 
    >>> hasNumbers("I own 1 dog")
    True
    >>> hasNumbers("I own no dog")
    False
    

    Alternatively you can use a Regular Expression, like this

    >>> import re
    >>> def hasNumbers(inputString):
    ...     return bool(re.search(r'\d', inputString))
    ... 
    >>> hasNumbers("I own 1 dog")
    True
    >>> hasNumbers("I own no dog")
    False
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2020-11-22 12:05
    alp_num = [x for x in string.split() if x.isalnum() and re.search(r'\d',x) and 
    re.search(r'[a-z]',x)]
    
    print(alp_num)
    

    This returns all the string that has both alphabets and numbers in it. isalpha() returns the string with all digits or all characters.

    0 讨论(0)
提交回复
热议问题