Open In App

Check If String is Integer in Python

Last Updated : 29 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will explore different possible ways through which we can check if a string is an integer or not. We will explore different methods and see how each method works with a clear understanding.

Example:

Input2 : "geeksforgeeks"
Output2 : geeksforgeeks is not an Intiger
Explanation : "geeksforgeeks" is a string but cannot be converted into integer through type casting.

Check If The String Is Integer In Python

Below we have discussed some methods through which we can easily check if the given string is integer or not in Python. Let’s see the methods:

Checking If The String Is Integer Using isdigit()

In Python, isdigit() is a string method that is used to determine whether the characters of a string are digits or not. So in this method, we are going to use this property to determine whether a given string is an integer value or not. Let’s move to the code implementation.

Explanation: We can clearly see that it detects “-1245” as an integer value and “geeksforgeeks” as a non-integer value. We also covered an edge case where the entered string might contain a sign (i.e. +,- ) as starting. First of all, we are checking if the string has any symbol as its starting character, if true then we remove the first character of the string and check for the remaining characters if it’s an integer value.

Python3




# check function
def checkInteger(s):
 
    # checking if it conatins sign such as
    if s[0] in ["+", "-"]:
        if s[1:].isdigit():
            return True
        return False
       
    if s.isdigit():
        return True
    return False
 
 
# Main Function
if __name__ == "__main__":
    s1 = "-12345"
    s2 = "geeksforgeeks"
 
    if checkInteger(s1): # Example 1
        print("{} is an Integer".format(s1))
    else:
        print("{} is not an Integer".format(s1))
 
    if checkInteger(s2): # Example
        print("{} is an Integer".format(s2))
    else:
        print("{} is not an Integer".format(s2))


Output

-12345 is an Integer
geeksforgeeks is not an Integer

Check If The String Is Integer Using Regular Expressions (regex module)

Regular Expressions in short regex is a powerful tool used for pattern matching. In this method, we are going to use Python’s re module to check if the string can be converted into integer or not. Lets see the code implementation.

Explanation : In the above out we can clearly notice that “12345” is detected as an integer whereas “geekforgeeks” is detected as a non-integer value. We have created a regex pattern above and match our input string with this created pattern.

Breakdown of the pattern:

  • [+-]? : This part allows to check if entered string contains any sign i.e. +,-. If it does or not, it validates the string. But if we remove this statement, we cannot add +,- as starting character of the string. If we do, then it will fall under a non-integer value.
  • [0-9]+ : This part checks if the input string has one or more digits. “+” sign insures that it will have at least one digit.

Python3




import re
 
def checkInteger(s):
    # our created pattern to check for the integer value
    if re.match('^[+-]?[0-9]+$', s):
        print("{} is an Integer".format(s))
    else:
        print("{} is not an Integer".format(s))
 
 
# Main Function
if __name__ == "__main__":
 
    checkInteger("12345")
    checkInteger("geeksforgeeks")


Output

12345 is an Integer
geeksforgeeks is not an Integer

Checking If The String Is Integer Using Explicit Type Casting

Explicit type casting is a type conversion of one variable data type into another data type, which is done by the programmer. In this method we are going to use explicit type casing along with try and except block of python. Lets see the code implementation.

Explanation : We can clearly observe that that “12345” is detected as an integer whereas “geekforgeeks” is detected as a non-integer value. We have performed explicit type casting under try block. If string successfully converted into an integer value than no doubt its an integer, otherwise under expect block we have displayed a message along with an error message.

Python3




# check function
def checkInteger(s):
   # try block
    try:
        # explicit type casting
        s = int(s)
        print("{} is an Integer".format(s))
    except ValueError as e:
        print("{} is not an Integer, error : {}".format(s, e))
 
 
# Main Function
if __name__ == "__main__":
   
    checkInteger("12345")
    checkInteger("geeksforgeeks")


Output

12345 is an Integer
geeksforgeeks is not an Integer, error : invalid literal for int() with base 10: 'geeksforgeeks'

Conclusion

We can check is an entered String is integer or not through various methods. We have checked for an integer value with the methods which include .isdigit(), re module(regex) and explicit type casting along with the try and except block. In this article, we have covered all the points with clear and concise examples along with their respective explanations and time and space complexities.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads