Python Check if a String Contains Numbers
In Python, we can use multiple methods to check whether a string contains numbers. The following is a simple example that usesany()function andisdigit()method to implement this functionality.
Example
def contains_number(s):
return any(char.isdigit() for char in s)
# Test
test_string = "Hello123"
if contains_number(test_string):
print(The string contains digits)
else:
print(The string does not contain digits)
return any(char.isdigit() for char in s)
# Test
test_string = "Hello123"
if contains_number(test_string):
print(The string contains digits)
else:
print(The string does not contain digits)
Code analysis:
contains_number(s)is a function that takes a stringsas a parameter.any(char.isdigit() for char in s)Uses a generator expression to iterate over each character in the stringchar, and checks whether it is a digit (usingisdigit()method).any()The function returnsTrueif any character in the generator expression is a digit, otherwise it returnsFalse。- In the test section, we define a string
test_string, and callcontains_number()function to check whether it contains digits.
Output result:
The string contains digits.Other extensions