Check if a string contains a number

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

提交回复
热议问题