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, we can use several methods to determine whether a string contains digits. The following simple example shows how to do this with the any() function and the str.isdigit() method.

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 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 and check whether it is a digit (char.isdigit() Return True if the character is a digit).
  3. any() function returns True If any element of the generator expression is True; otherwise, returns False。
  4. in the test string test_string = "Hello123" in,contains_number(test_string) returns True, because the string contains digits.

Output result:

字符串包含数字

Document Object Reference Manual Python3 Examples