Python Check Whether a String Consists of Digits
We can use Python's str.isdigit() method to determine whether a string consists entirely of digits. This method returns a boolean: it returns True; otherwise, returns False。
Example
def
is_all_digits
(
s
)
:
return
s.
isdigit
(
)
Testing
test_string1
=
"12345"
test_string2
=
"123a45"
(
is_all_digits
(
test_string1
)
)
Output True
(
is_all_digits
(
test_string2
)
)
Output False
Code analysis:
s.isdigit(): This is a string method used to check whether the stringsconsists entirely of digits.test_string1andtest_string2: These are two test strings, used to testisdigit()method.print(is_all_digits(test_string1)): Print the value ofTrue, becausetest_string1consists entirely of digits.print(is_all_digits(test_string2)): Print the value ofFalse, becausetest_string2contains non-digit charactersa。
Output result:
True
False
Python3 Examples