Check if a string contains a number

Use the Python method str.isalpha(). This function returns True if all characters in the string are alphabetic and there is at least one character; returns False otherwise.

Python Docs: https://docs.python.org/3/library/stdtypes.html#str.isalpha


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

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

Tags:

Python

String