HiveBrain v1.2.0
Get Started
← Back to all entries
snippetpythonCritical

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

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
representshowintexceptusingtrycancheckwithoutstring

Problem

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

Solution

If you're really just annoyed at using try/excepts all over the place, please just write a helper function:

def represents_int(s):
    try: 
        int(s)
    except ValueError:
        return False
    else:
        return True


>>> print(represents_int("+123"))
True
>>> print(represents_int("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.

Code Snippets

def represents_int(s):
    try: 
        int(s)
    except ValueError:
        return False
    else:
        return True
>>> print(represents_int("+123"))
True
>>> print(represents_int("10.0"))
False

Context

Stack Overflow Q#1265665, score: 517

Revisions (0)

No revisions yet.