Python Check if a String Contains Numbers

Python3 Examples

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)

Code analysis:

  1. contains_number(s)is a function that takes a stringsas a parameter.
  2. 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).
  3. any()The function returnsTrueif any character in the generator expression is a digit, otherwise it returnsFalse。
  4. In the test section, we define a stringtest_string, and callcontains_number()function to check whether it contains digits.

Output result:

The string contains digits.

Python3 Examples

Other extensions