Summary: In this Python tutorial, we will learn different ways to check if a given string is actually an integer.
For example, “123” is of type string but the value is actually an integer.
There are many ways to test this in Python. Let’s see each of them one by one.
Method 1: Using int()
In this method, we try to attempt to cast the string into an integer using the inbuilt
If the string is not an integer then the Python will throw the
ValueError otherwise not.
def is_integer(n): try: int(n) return True except ValueError: return False is_integer("456") #returns True is_integer("-456") #returns True is_integer("p456") #returns False
Method 2: Using isdigit()
isdigit() method, when used on a string, returns true if all the characters in the string are digits and otherwise false.
"123".isdigit() #return True "-123".isdigit() #return False
The drawback of the
isdigit() method is that it can only testify the non-negative integers. It is so because it interprets ‘-‘ as a special character.
Method 3: Using isnumeric()
isnumeric() is another method similar to
isdigit() checks whether a string is a number.
The advantage of this method over
isdigit() is that it works both for negative and positive integers.
"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 suggestions then comment below.