Hi,
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?
is_int('3.14') = False
is_int('-7') = True
Thanks,
Adam
Hi,
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?
is_int('3.14') = False
is_int('-7') = True
Thanks,
Adam
If you only deal with numeric values, one method could be to compare the int() and float() casts, but this will break when testing a string. (not to mention this can be expensive on large sets)
def isinteger(x):
return int(x) == float(x)
with positive integers you could use .isdigit
:
>>> '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.
edit:
def check_int(s):
if s[0] in ('-', '+'):
return s[1:].isdigit()
return s.isdigit()
Use a regular expression:
import re
def RepresentsInt(s):
return re.match(r"[-+]?\d+$", s) is not None
If you must accept decimal fractions also:
def RepresentsInt(s):
return re.match(r"[-+]?\d+(\.0*)?$", s) is not None
For improved performance if you're doing this often, compile the regular expression only once using re.compile()
.
Greg Hewgill's approach was missing a few components: the leading "^" to only match the start of the string, and compiling the re beforehand. But this approach will allow you to avoid a try: exept:
import re
INT_RE = re.compile(r"^[-]?\d+$")
def RepresentsInt(s):
return INT_RE.match(str(s)) is not None
I would be interested why you are trying to avoid try: except?
If you're really just annoyed at using try/except
s 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.