A lot of times, while doing some projects or maybe simple programming, we need to curb whether a given Python string is an integer or not. So, in this detailed article, you will get to know about five dominant ways to check if a given python string is an integer or not.
So, without wasting anytime let’s directly jump to the ways for python check if string is integer.
Some Elite Ways to Python Check if String is Integer
- isnumeric function
- exception handling
- isdigit function
- Regular Expression
1. Checking If Given or Input String is Integer or Not Using isnumeric Function
Python’s isnumeric() function can be used to test whether a string is an integer or not. The isnumeric() is a builtin function. It returns True if all the characters are numeric, otherwise False.
isnumeric() method doesn’t take any parameters.
#1 s = '695444' print(s.isnumeric()) #2 s = '\u00BD' print(s.isnumeric()) #3 s='pythonpool65' print(s.isnumeric()) #4 s = '5651' if s.isnumeric(): print('Integer') else: print('Not an integer')
True True False Integer
Here in the above example we have used isnumeric() function to check if string is integer in python in four different ways.
- In the first example, we have initialized and declared a string s with value ‘69544’. After that, with the isnumeric() function, we checked if ‘69544’ is an integer or not. In this case, it is an integer so, and it returned ‘True.’
- In the second example to python check, if the string is an integer, we have initialized a string s with value ‘\u00BD’. This ‘\u00BD’ is a Unicode value, and you can write the digit and numeric characters using Unicode in the program. So, it returns true.
- The third example is similar to the first one, but instead of declaring a value of an integer, we have combined both integer value and string. In this case, the isnumeric() function will return False.
- In the fourth example, we have done some extra steps, using if-else with the fusion of isnumeric() function. Here we declared and initialized our variable ‘s’ with the value of ‘5651’. Then with the help of flow control statements and isnumeric() function, we checked whether the given string is an integer or not. In this case, it is an integer. So, we will get an output saying Integer. In other cases, if the value is not an integer, then we will get a result saying ‘Not an integer.’
Note: This method of checking if the string is an integer in Python will not work in negative numbers.
2. Python Check If The String is Integer Using Exception Handling
We can use python check if the string is integer using the exception handling mechanism. If you don’t know how the exception is handled in python, let me briefly explain it to you. In Python, exceptions could be handled utilizing a try statement. The vital operation which could raise an exclusion is put within the try clause. The code that manages the exceptions is written in the except clause. We can thus choose what operations to do once we’ve caught the exclusion.
Let’s see through an example how it works.
try: # Code except: # Code
exception-handling mechanism (try-except-finally) doesn’t take any parameters.
s = '951sd' isInt = True try: # converting to integer int(s) except ValueError: isInt = False if isInt: print('Input value is an integer') else: print('Not an integer')
Not an integer
In the above example, we have initialized a sting ‘s’ with value ‘951sd’. Initially, we believe that the value of string ‘s’ is an integer. So we declared it true. After that, we Tried to convert string to an integer using
If the string ‘s’ contains non-numeric characters, then ‘int’ will throw a ValueError, which will indicate that the string is not an integer and vice-versa.
Also along with the exception-handling mechanism, we have used the flow control statements to print the output accordingly.
Note: This method of checking if the string is an integer in Python will also work on Negative Numbers.
3. Python Check If The String is Integer Using isdigit Function
We can use the isdigit() function to check if the string is an integer or not in Python. The isdigit() method returns True if all characters in a string are digits. Otherwise, it returns False.
Let’s see through an example how it works.
isdigit() method doesn’t take any parameters.
Return Value of isdigit() Function
- Returns True – If all characters in the string are digits.
- Returns False – If the string contains one or more non-digits
str = input("Enter any value: ") if str.isdigit(): print("User input is an Integer ") else: print("User input is string ")
Enter any value :698 User input is Integer
The third example to check if the input string is an integer is using the isdigit() function. Here in the above example, we have taken input from string and stored it in the variable ‘str.’ After that, with the help of control statements and the isdigit() function, we have verified if the input string is an integer or not.
'isdigit()‘ function will work only for positive integer numbers. i.e., if you pass any float number, it will say it is a string.
It does not take any arguments, therefore it returns an error if a parameter is passed
4. Python Check If The String is Integer Using Regular Expression
We can use the search pattern which is known as a regular expression to check if a string is an integer or not in Python. If you don’t know what is regular expression and how it works in python, let me briefly explain it to you. In Python, a regular expression is a particular sequence of characters that makes it possible to match or find other strings or sets of strings, with a specialized syntax held at a pattern. Regular expressions are widely utilized in the UNIX world.
Here we are using match method of regular expression i.e, re.match().
Re.match() searches only in the first line of the string and return match object if found, else return none. But if a match of substring is located in some other line aside from the first line of string (in case of a multi-line string), it returns none.
Let’s see through an example how it works.
re.match(pattern, string, flags=0)
It contains the regular expression that is to be matched.
It comprises of the string that would be searched to match the pattern at the beginning of the string.
- flags (optional)
You can specify different flags using bitwise OR (|). These are modifiers.
- Return match objects if found.
- If there is no match, the value
Nonewill be returned, instead of the Match Object.
import re value = input("Enter any value: ") result = re.match("[-+]?\d+$", value) if result is not None: print("User input is an Integer") else: print("User Input is not an integer")
Enter any value: 965oop User Input is not an integer
The fourth way to check if the input string is an integer or not in Python is using the Regular Expression mechanism. Here in this example first we have imported regular expression using ‘import re’. After that, we have taken input from the user and stored it in variable value. Then we have used our method re.match() to check if the input string is an integer or not. The pattern to be matched here is “[-+]?\d+$”. This pattern indicates that it will only match if we have our input string as an integer.
're.match()‘ function will also work with negative numbers as well.
5. Python Check If The String is Integer Using
We can use the combination of any() and map() function to check if a string is an integer or not in Python. If you don’t know what are any() and map() functions and how they work in python, let me briefly explain it to you.
- The any() function takes an iterable (list, string, dictionary etc.) in Python. This function return true if any of the element in iterable is true, else it returns false.
map()function calls the specified function for each item of an iterable (such as string, list, tuple or dictionary) and returns a list of results.
Let’s see through examples of how they work.
any() Function Syntax
map() Function Syntax
map(function, iterable [, iterable2, iterable3,...iterableN])
any() Function Parameters
An iterable object (list, tuple, dictionary)
Parameters of map() Function
The function to execute for each item
A sequence, collection or an iterator object. You can send as many iterables as you like, just make sure the function has one parameter for each iterable.
- Any: The any() function returns True if any item in an iterable is true, otherwise, it returns False.
- Map: Returns a list of the results after applying the given function
input = "sdsd" contains_digit = any(map(str.isdigit, input)) print(contains_digit)
The fifth way to check if the input string is an integer or not in Python is by using the combination of any() and map() function in python. Here in the above example, we have taken input as a string which is ‘sdsd’. And after that with the help of any(), map(), and isdigit() function, we have python check if the string is an integer.
We get False because the input string is ‘sdsd’.
This method will also work with negative numbers.
Applications of Python Check If String is Integer
- To check whether a given string variable or value contains only integers such as validating if user input the correct numeric option in a menu based application.
- Using ascii values of characters, count and print all the digits using isdigit() function.
- Introduction to Python Super With Examples
- Python Help Function
- Why is Python sys.exit better than other exit functions?
- Python Bitstring: Classes and Other Examples | Module
Conclusion: Python Check If String is Integer
So if you make it till the end, I am pretty sure you now be able to understand all the possible ways to Check if a String is Integer in Python. The best possible way to check if string is integer in Python depends on your need and the type of project you are doing. I think you might also want to know Ways in Python to Sort the List of Lists. If yes there is an awesome tutorial available in our library of tutorials do check it out.
Still have any doubts or questions do let me know in the comment section below. I will try to help you as soon as possible.