Check if a string contains a number
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.