[python] How can I check if a string represents an int, without using try/except?

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

This question is related to python string integer

The answer is

with positive integers you could use .isdigit:

>>> '16'.isdigit()

it doesn't work with negative integers though. suppose you could try the following:

>>> s = '-17'
>>> s.startswith('-') and s[1:].isdigit()

it won't work with '16.0' format, which is similar to int casting in this sense.


def check_int(s):
    if s[0] in ('-', '+'):
        return s[1:].isdigit()
    return s.isdigit()

Similar questions with python tag:

Similar questions with string tag:

Similar questions with integer tag: