check if a string contains a number
Most of the q 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.
>>> 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
★ Back to homepage or read more recommendations: