Check if a string contains a number

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

    You can accomplish this as follows:

    if a_string.isdigit(): do_this() else: do_that()

    https://docs.python.org/2/library/stdtypes.html#str.isdigit

    Using .isdigit() also means not having to resort to exception handling (try/except) in cases where you need to use list comprehension (try/except is not possible inside a list comprehension).

    0 讨论(0)
  • 2020-11-22 11:43

    You can use NLTK method for it.

    This will find both '1' and 'One' in the text:

    import nltk 
    
    def existence_of_numeric_data(text):
        text=nltk.word_tokenize(text)
        pos = nltk.pos_tag(text)
        count = 0
        for i in range(len(pos)):
            word , pos_tag = pos[i]
            if pos_tag == 'CD':
                return True
        return False
    
    existence_of_numeric_data('We are going out. Just five you and me.')
    
    0 讨论(0)
  • 2020-11-22 11:43

    I'm surprised that no-one mentionned this combination of any and map:

    def contains_digit(s):
        isdigit = str.isdigit
        return any(map(isdigit,s))
    

    in python 3 it's probably the fastest there (except maybe for regexes) is because it doesn't contain any loop (and aliasing the function avoids looking it up in str).

    Don't use that in python 2 as map returns a list, which breaks any short-circuiting

    0 讨论(0)
  • 2020-11-22 11:43

    What about this one?

    import string
    
    def containsNumber(line):
        res = False
        try:
            for val in line.split():
                if (float(val.strip(string.punctuation))):
                    res = True
                    break
        except ValueError:
            pass
        return res
    
    containsNumber('234.12 a22') # returns True
    containsNumber('234.12L a22') # returns False
    containsNumber('234.12, a22') # returns True
    
    0 讨论(0)
  • 2020-11-22 11:47

    This probably isn't the best approach in Python, but as a Haskeller this lambda/map approach made perfect sense to me and is very short:

    anydigit = lambda x: any(map(str.isdigit, x))

    Doesn't need to be named of course. Named it could be used like anydigit("abc123"), which feels like what I was looking for!

    0 讨论(0)
  • 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)
    
    0 讨论(0)
提交回复
热议问题