Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a string contains a number

Tags:

python

string

People also ask

How do you check if a string has a number in it Python?

str. isdigit() returns True if all the characters in the given string are digits, False otherwise. If stringExample contains at least a number, then the above code returns True because chr. isdigit() for chr in stringExample has at least one True in the iterable.

How do you check if there is a number in a string Java?

Use the isDigit() Method to Check if String Contains Numbers in Java. To find an integer from a string, we can use this in-built function called isDigit() .


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

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

Alternatively you can use a Regular Expression, like this

>>> import re
>>> def has_numbers(inputString):
...     return bool(re.search(r'\d', inputString))
... 
>>> has_numbers("I own 1 dog")
True
>>> has_numbers("I own no dog")
False

You can use a combination of any and str.isdigit:

def num_there(s):
    return any(i.isdigit() for i in s)

The function will return True if a digit exists in the string, otherwise False.

Demo:

>>> king = 'I shall have 3 cakes'
>>> num_there(king)
True
>>> servant = 'I do not have any cakes'
>>> num_there(servant)
False

use

str.isalpha() 

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

Return true if all characters in the string are alphabetic and there is at least one character, false otherwise.


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

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)

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.')

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).