Is there any way to tell whether a string represents an integer (e.g., '3'
, '-17'
but not '3.14'
or 'asfasfas'
) Without using a try/except mechanism?
JavaScript
x
3
1
is_int('3.14') == False
2
is_int('-7') == True
3
Advertisement
Answer
If you’re really just annoyed at using try/except
s all over the place, please just write a helper function:
JavaScript
1
8
1
def represents_int(s):
2
try:
3
int(s)
4
except ValueError:
5
return False
6
else:
7
return True
8
JavaScript
1
5
1
>>> print(represents_int("+123"))
2
True
3
>>> print(represents_int("10.0"))
4
False
5
It’s going to be WAY more code to exactly cover all the strings that Python considers integers. I say just be pythonic on this one.