Check If String is Integer in Python
Last Updated :
02 Apr, 2025
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.
Python
# check function
def checkInteger(s):
# checking if it contains 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 2
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.
Python
import re
def checkInteger(s):
# our created pattern to check for the integer value
if re.match(r'^[+-]?[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")
Output12345 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.
Python
# 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")
Output12345 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.
Similar Reads
Convert integer to string in Python In this article, weâll explore different methods for converting an integer to a string in Python. The most straightforward approach is using the str() function.Using str() Functionstr() function is the simplest and most commonly used method to convert an integer to a string.Pythonn = 42 s = str(n) p
2 min read
Convert Hex String To Integer in Python Hexadecimal representation is commonly used in computer science and programming, especially when dealing with low-level operations or data encoding. In Python, converting a hex string to an integer is a frequent operation, and developers have multiple approaches at their disposal to achieve this tas
2 min read
How to convert string to integer in Python? In Python, a string can be converted into an integer using the following methods : Method 1: Using built-in int() function: If your string contains a decimal integer and you wish to convert it into an int, in that case, pass your string to int() function and it will convert your string into an equiv
3 min read
Python - Check for float string Checking for float string refers to determining whether a given string can represent a floating-point number. A float string is a string that, when parsed, represents a valid float value, such as "3.14", "-2.0", or "0.001".For example:"3.14" is a float string."abc" is not a float string.Using try-ex
2 min read
Convert String to Int in Python In Python, converting a string to an integer is important for performing mathematical operations, processing user input and efficiently handling data. This article will explore different ways to perform this conversion, including error handling and other method to validate input string during conver
3 min read
Check If Value Is Int or Float in Python In Python, you might want to see if a number is a whole number (integer) or a decimal (float). Python has built-in functions to make this easy. There are simple ones like type() and more advanced ones like isinstance(). In this article, we'll explore different ways to check if a value is an integer
4 min read
How to take integer input in Python? In this post, We will see how to take integer input in Python. As we know that Python's built-in input() function always returns a str(string) class object. So for taking integer input we have to type cast those inputs into integers by using Python built-in int() function.Let us see the examples:Exa
3 min read
Convert String to Long in Python Python defines type conversion functions to directly convert one data type to another. This article is aimed at providing information about converting a string to long. Converting String to long A long is an integer type value that has unlimited length. By converting a string into long we are transl
1 min read
Check if String Contains Substring in Python This article will cover how to check if a Python string contains another string or a substring in Python. Given two strings, check whether a substring is in the given string. Input: Substring = "geeks" String="geeks for geeks"Output: yesInput: Substring = "geek" String="geeks for geeks"Output: yesEx
8 min read
Check for True or False in Python Python has built-in data types True and False. These boolean values are used to represent truth and false in logical operations, conditional statements, and expressions. In this article, we will see how we can check the value of an expression in Python.Common Ways to Check for True or FalsePython pr
2 min read