Is there any way to tell whether a string represents an integer (e.g.,
'-17' but not
'asfasfas') Without using a try/except mechanism?
is_int('3.14') = False is_int('-7') = True
If you're really just annoyed at using
try/excepts all over the place, please just write a helper function:
def RepresentsInt(s): try: int(s) return True except ValueError: return False >>> print RepresentsInt("+123") True >>> print RepresentsInt("10.0") False
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.
with positive integers you could use
>>> '16'.isdigit() True
it doesn't work with negative integers though. suppose you could try the following:
>>> s = '-17' >>> s.startswith('-') and s[1:].isdigit() True
it won't work with
'16.0' format, which is similar to
int casting in this sense.
def check_int(s): if s in ('-', '+'): return s[1:].isdigit() return s.isdigit()