Python Determine if String Is Composed of Digits
We can use Python'sstr.isdigit()method to determine whether a string is composed entirely of digits. This method returns a boolean value. If all characters in the string are digits, it returnsTrue, otherwise it returnsFalse。
Example
def is_all_digits(s):
return s.isdigit()
# Test
test_string1 = "12345"
test_string2 = "123a45"
print(is_all_digits(test_string1)) # Output True
print(is_all_digits(test_string2)) # Output False
return s.isdigit()
# Test
test_string1 = "12345"
test_string2 = "123a45"
print(is_all_digits(test_string1)) # Output True
print(is_all_digits(test_string2)) # Output False
Code explanation:
s.isdigit(): This is a string method used to check whether the stringsis composed entirely of digits.test_string1andtest_string2: These are two test strings, used to test theisdigit()method.print(is_all_digits(test_string1)): OutputTrue, becausetest_string1is composed entirely of digits.print(is_all_digits(test_string2)): OutputFalse, becausetest_string2contains non-digit charactersa。
Output result:
True FalseOther Extensions
Python3 Examples