5 Ways to Check if a String is Integer in Python

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
  • any() and map() functions

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.

Note: isnumeric doesn’t check if the string represents an integer, it checks if all the characters in the string are numeric characters. \u00BD' is unicode for ½, which is not integer. But '\u00BD'.isnumeric() still returns True.

Use different method is you want to avoid these cases.

Syntax

string.isnumeric()

Parameters

The isnumeric() method doesn’t take any parameters.

Examples

#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')

Output

True
True
False
Integer

Explanation:

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.

Syntax

try: 
    # Code 
except: 
    # Code

Parameters

The exception-handling mechanism (try-except-finally) doesn’t take any parameters.

Examples

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')

Output

Not an integer

Explanation:

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 int function.
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.

Syntax

string.isdigit()

Parameters

The 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

Examples

str = input("Enter any value: ")

if str.isdigit():
    print("User input is an Integer ")
else:
    print("User input is string ")

Output

Enter any value :698
User input is Integer

Explanation:

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.

Note:
The '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.

Syntax

re.match(pattern, string, flags=0)

Parameters

  1. pattern
    It contains the regular expression that is to be matched.
  2. string
    It comprises of the string that would be searched to match the pattern at the beginning of the string.
  3. flags (optional)
    You can specify different flags using bitwise OR (|). These are modifiers.

Return Value

  • Return match objects if found.
  • If there is no match, the value None will be returned, instead of the Match Object.

Examples

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")

Output

Enter any value: 965oop
User Input is not an integer

Explanation:

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.

Note:
The 're.match()‘ function will also work with negative numbers as well.

5. Python Check If The String is Integer Using any() and map() functions

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. 
  • The 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.

Syntax

any() Function Syntax

any(iterable)

map() Function Syntax

map(function, iterable [, iterable2, iterable3,...iterableN])

Parameters

any() Function Parameters

iterable:
An iterable object (list, tuple, dictionary)

Parameters of map() Function

function:
The function to execute for each item
iterable
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.

Return Value

  • 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

Examples

input = "sdsd"

contains_digit = any(map(str.isdigit, input))
print(contains_digit)

Output

False

Explanation:

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’.

Note:
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.

Python Check if String Contains Integer

To check whether a string has a number or not, we can use the re module(regex in python). Using re.search() function we can check if digit exists in the string. Here, /d is notation used in re for digit. 

Example: 

import re
str = "N123"
print(bool(re.search(r'\d', str)))
#Output is:TRUE

To check if a string contains an integer or a numeric value only , you can use str.isnumeric(). It is a part of the regex module in python. Here is a sample piece of code:

import re
my_str = '3468910'
print(my_str.isnumeric())  
if my_str.isnumeric():
    print('The string contains only numbers')
else:
    print('The string does NOT contain only numbers')

Python Check if String contains Int or Float

We can check for presence of integer or a numeric value using is.digit() function. To see if a float variable exists in string,we can check presence of a decimal. 

Example:

var= '10.4'
if var.isdigit():
   print ("Int")
elif var.replace('.','',1).isdigit() and var.count('.') < 2:
   print ("Float")
else:
   print ("neither int nor float")

Python Check if String is Hex Number

A hexadecimal number follows 16 bit coding. 

str = 'af'
all(i in string.hexdigits for i in str)

Here, with the help of string.hexdigits, we can check whether ‘0123456789abcdefABCDEF’ is present in string. It contains all possible hex digits. 

So Output is :

True

FAQs

How to check if string is a number regex in python?

You can use re.search() function. It checks if a digit exists in the string. Here, /d is notation used in re for digit. 
Example: 
print(bool(re.search(r’\d’, str)))

How to check if a string is a phone number in python?

You can use the regex module. \d refers to the presence of a digit which is 10 here and it will check the variable till the end.
Number = re.compile(r’^\d{10}$’)

Must Read

Conclusion

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.

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.

Happy Pythoning!

Subscribe
Notify of
guest
7 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
locquet
locquet
2 years ago

You can use the instruction strip too:
st = ‘-50’
if st.strip(“-“).isnumeric():
do something

Pratik Kinage
Admin
2 years ago
Reply to  locquet

Yes, that’s one more way to do that.

Regards,
Pratik

fdsa
fdsa
2 years ago
Reply to  locquet

what if it is ‘2.3’?

Pratik Kinage
Admin
2 years ago
Reply to  fdsa

Yes, that’ll be a problem for this specific string. But since ‘2.3’ is not an integer, it’s technically correct. If our intent was to check if the string is ‘number’ then that was incorrect.

Aditya Anand
Aditya Anand
2 years ago
Reply to  locquet

this is actually a good way to check for -ve nos

Turnip
Turnip
2 years ago

isnumeric doesn’t check if the string represents an integer, it checks if all the characters in the string are numeric characters. In the second example, '\u00BD' is unicode for ½, which is not integer. But '\u00BD'.isnumeric() still returns True.

Pratik Kinage
Admin
2 years ago
Reply to  Turnip

Nice catch! Learned something interesting today. Yes, then using isnumeric is not good. I’ve updated the article accordingly. Thank you for noticing this.