Check if a string contains a number

Posted on

Solving problem is about exposing yourself to as many situations as possible like Check if a string contains a number and practice these strategies over and over. With time, it becomes second nature and a natural way you approach any problems in general. Big or small, always start with a plan, use other strategies mentioned here till you are confident and ready to code the solution.
In this post, my aim is to share an overview the topic about Check if a string contains a number, which can be followed any time. Take easy to follow this discuss.

Check if a string contains a number

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 string.
I need to enter a string and check to see if it contains any numbers and if it does reject it.

The function isdigit() only returns True if ALL of the characters are numbers. I just want to see if the user has entered a number so a sentence like "I own 1 dog" or something.

Any ideas?

Answer #1:

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
Answered By: thefourtheye

Answer #2:

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
Answered By: aIKid

Answer #3:

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.

Answered By: K246

Answer #4:

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
Answered By: zyxue

Answer #5:

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)
Answered By: Haini

Answer #6:

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

Answered By: olisteadman

Answer #7:

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

Answer #8:

You can use range with count to check how many times a number appears in the string by checking it against the range:

def count_digit(a):
    sum = 0
    for i in range(10):
        sum += a.count(str(i))
    return sum
ans = count_digit("apple3rh5")
print(ans)
#This print 2
Answered By: pedmindset

Leave a Reply

Your email address will not be published. Required fields are marked *