Skip to content
Advertisement

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?

Advertisement

Answer

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
Advertisement