Python Check Whether a String Contains Digits
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
)
:
(
"The string contains digits"
)
else
:
(
"The string does not contain digits"
)
Code analysis:
contains_number(s)is a function that takes a stringsas its argument.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()ReturnTrueif the character is a digit).any()function returnsTrueIf any element of the generator expression isTrue; otherwise, returnsFalse。- in the test string
test_string = "Hello123"in,contains_number(test_string)returnsTrue, because the string contains digits.
Output result:
字符串包含数字
Python3 Examples