Today we will discuss how to check whether a string is actually an integer in python.

For example, “123” is of type string but it contains purely an integer.

There are many ways to test whether a Python string contains an integer, let’s see each of them one by one.

Method 1:

Try casting the string into integer using int(). The operation will be successful without any error if the string contains only numbers otherwise it will throw ValueError. So use try and catch for handling the error.

def is_integer(n):
        return True
    except ValueError:
        return False

is_integer("456")  #returns True
is_integer("-456") #returns True
is_integer("p456") #returns False

Method 2:

Use isdigit() method of string class. It returns true if all the characters in the string are digits and False if at least one of them is a character.

"123".isdigit()  #return True
"-123".isdigit() #return False

Use isdigit() method to check for non negative values as it interpret “-” (negative) as a character so it return false for negative numbers.

Method 3:

isnumeric() is another method of string class and perform operation similar as isdigit() method, as dicussed earlier.

"879".isnumeric()      #return True
"-44".isnumeric()      #return False
"pencil7".isnumeric()  #return False

I hope now you can easily check for numbers in a python string. If you have any doubts or suggestion then comment below.

Leave a Reply

five × one =