Check if a string contains a number

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

    You could apply the function isdigit() on every character in the String. Or you could use regular expressions.

    Also I found How do I find one number in a string in Python? with very suitable ways to return numbers. The solution below is from the answer in that question.

    number = re.search(r'\d+', yourString).group()
    

    Alternatively:

    number = filter(str.isdigit, yourString)
    

    For further Information take a look at the regex docu: http://docs.python.org/2/library/re.html

    Edit: This Returns the actual numbers, not a boolean value, so the answers above are more correct for your case

    The first method will return the first digit and subsequent consecutive digits. Thus 1.56 will be returned as 1. 10,000 will be returned as 10. 0207-100-1000 will be returned as 0207.

    The second method does not work.

    To extract all digits, dots and commas, and not lose non-consecutive digits, use:

    re.sub('[^\d.,]' , '', yourString)
    

提交回复
热议问题