Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python Check Whether a String Contains Digits

Python Check Whether a String Contains Digits

Document Object Reference Manual Python3 Examples

In Python there are several ways to check whether a string contains digits. Below is a simple example using any() function and the isdigit() method to implement it.

Example

def

contains_number

(

s

)

:

   

return

any

(

char.

isdigit

(

)

for

char

in

s

)

Testing

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 string s as its argument.
  2. any(char.isdigit() for char in s) Use a generator expression to iterate over each character in the string charand check whether it is a digit (using the isdigit() method).
  3. any() function returns True if any character in the generator expression is a digit, otherwise it returns False。
  4. In the test section we define a string test_stringand call the contains_number() function to check whether it contains digits.

Output result:

字符串包含数字

Document Object Reference Manual Python3 Examples