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?


Solution 1:

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

Solution 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

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

Solution 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