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.

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.

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.

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