How can I determine if a string can be an integer in Python. For example: if I write functions named digit() and nondigit(). The string must be either just digits (1-9) or letters.
str1 = '4582'
str1.digit() == True
str2 = '458dfr'
str2.digit() == False
str3 = 'abcd'
str3.nondigit() == True
str4 = '258edcx'
str4.nondigit() == False
str
objects have an isdigit
method which accomplishes one of your tasks. From a broader perspective, it's better to just try it and see:
def digit(s):
try:
int(s)
return True
except ValueError:
return False
For example, " 1234 ".isdigit()
is False
(there are spaces), but python can convert it to an int
, so my digit
function is True
.