Python Check if a String Contains Digits

Python3 Examples

In Python, we can use multiple methods to determine whether a string contains digits. The following is a simple example showing how to useany()functions andstr.isdigit()methods to implement this functionality.

Example

def contains_number(s):
    return any(char.isdigit() for char in s)

# Test string
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 string and check whether the character is a digit (char.isdigit()returnsTrueif the character is a digit).
  3. any()The function will returnTrueif any element in the generator expression isTrue, otherwise it returnsFalse。
  4. In the test stringtest_string = "Hello123",contains_number(test_string)will returnTrue, because the string contains digits.

Output result:

The string contains digits.

Python3 Examples

Other extensions