To check if a string contains numbers in Python, you can create a function, loop over the string and check if any of the characters are numeric with isnumeric().
a = "hello1"
b = "bye"
c = "123"
def containsNumbers(s):
contains = False
for char in s:
if isnumeric(char):
contains = True
return contains
print(containsNumbers(a))
print(containsNumbers(b))
print(containsNumbers(c))
#Output:
True
False
True
You can also use the isdigit() function.
a = "hello1"
b = "bye"
c = "123"
def containsNumbers(s):
contains = False
for char in s:
if char.isdigit():
contains = True
return contains
print(containsNumbers(a))
print(containsNumbers(b))
print(containsNumbers(c))
#Output:
True
False
True
When working with strings in Python, the ability to check these strings for certain conditions is very valuable.
One such case is if you want to check if a string variable contains numbers or not.
To check if a string contains numbers in Python, you can create a function, loop over the string and check if any of the characters are numeric with isnumeric().
isnumeric() allows us to check if a string is numeric or not, i.e. a number between 0 to 9.
If one of the characters in a given string is numeric, then we can conclude that our string contains numbers.
Below is a function which will check if a string contains numbers in Python.
a = "hello1"
b = "bye"
c = "123"
def containsNumbers(s):
contains = False
for char in s:
if isnumeric(char):
contains = True
return contains
print(containsNumbers(a))
print(containsNumbers(b))
print(containsNumbers(c))
#Output:
True
False
True
Checking if String Contains Number with isdigit() in Python
Another method you can use to check if a string contains any number is to use the isdigit() function in a loop.
We can take the function from above and just adjust the line where we check if the character is numeric.
isdigit() returns True if all characters in a string are numbers.
Below is a function which will check if a string contains numbers in Python with isdigit().
a = "hello1"
b = "bye"
c = "123"
def containsNumbers(s):
contains = False
for char in s:
if char.isdigit():
contains = True
return contains
print(containsNumbers(a))
print(containsNumbers(b))
print(containsNumbers(c))
#Output:
True
False
True
Checking If String Does Not Contain Numbers in Python
If you want to check if a string does not contain numbers in Python, then you can modify the function from above slightly.
To check if a string doesn’t contain numbers, we want to negate the ‘contains’ variable.
Below is a different function which will check if a string does not contain numbers in Python.
a = "hello1"
b = "bye"
c = "123"
def doesNotContainNumbers(s):
doesNotContain = True
for char in s:
if isnumeric(char):
doesNotContain = False
return doesNotContain
print(containsNumbers(a))
print(containsNumbers(b))
print(containsNumbers(c))
#Output:
False
True
False
Hopefully this article has been useful for you to learn how to check if a string contains numbers or not.