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
JavaScript
x
8
1
def has_numbers(inputString):
2
return any(char.isdigit() for char in inputString)
3
4
has_numbers("I own 1 dog")
5
# True
6
has_numbers("I own no dog")
7
# False
8
Alternatively you can use a Regular Expression, like this
JavaScript
1
9
1
import re
2
def has_numbers(inputString):
3
return bool(re.search(r'd', inputString))
4
5
has_numbers("I own 1 dog")
6
# True
7
has_numbers("I own no dog")
8
# False
9