Python Check Whether a String Contains Digits
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
)
:
(
"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 stringcharand check whether it is a digit (using theisdigit()method).any()function returnsTrueif any character in the generator expression is a digit, otherwise it returnsFalse。- In the test section we define a string
test_stringand call thecontains_number()function to check whether it contains digits.
Output result:
字符串包含数字
Python3 Examples