Check if a string contains a number

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

    any and ord can be combined to serve the purpose as shown below.

    >>> def hasDigits(s):
    ...     return any( 48 <= ord(char) <= 57 for char in s)
    ...
    >>> hasDigits('as1')
    True
    >>> hasDigits('as')
    False
    >>> hasDigits('as9')
    True
    >>> hasDigits('as_')
    False
    >>> hasDigits('1as')
    True
    >>>
    

    A couple of points about this implementation.

    1. any is better because it works like short circuit expression in C Language and will return result as soon as it can be determined i.e. in case of string 'a1bbbbbbc' 'b's and 'c's won't even be compared.

    2. ord is better because it provides more flexibility like check numbers only between '0' and '5' or any other range. For example if you were to write a validator for Hexadecimal representation of numbers you would want string to have alphabets in the range 'A' to 'F' only.

提交回复
热议问题