Many times we need 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.
This article will list out 3 commonly used methods to check if a string is an integer in python.

Method 1: Using try-except block
Python’s exception handling mechanism can be used to test whether a string is an integer. Try to convert string to an integer using int function.
If the string contains non-numeric characters, then int will throw a ValueError which will clearly indicate that the string is not a complete integer. Example,

str = '123a'
is_int = True
try:
   # convert to integer
   int(str)
except ValueError:
   is_int = False
# print result
if is_int:
   print('Integer value')
else:
   print('Not an integer')

Above code will print

Not an Integer

This method also works on negative integer values.
Method 2: Using isnumeric function
If you want to check if a string is numeric without using exception handling or try-except block, then this method should be used.
Python’s inbuilt function isnumeric is invoked on a string and checks whether the string contains only numeric characters.
It returns True if the string contains only integers and False if it has any character other than numeric. Example,

str = '123'
if str.isnumeric():
   print('Integer value')
else:
   print('Not an integer')
This method will not work on negative values.
Method 3: Using isdigit function
This method works the same as previous method and returns True if the string contains only numeric digits and False otherwise. Example,

str = '123'
if str.isdigit():
   print('Integer value')
else:
   print('Not an integer')

This code will print

Integer value

This method will not work on negative values.

Method 4: Using regular expression
Regular expression can be used to check the presence of any character in a given string.
Python provides re module which has methods to apply regular expression on a string and return the result.
re module has a method match which takes a regular expression pattern and the string to be checked for regular expression as arguments and returns the matched portion of string.
It returns None if there is no match for that regular expression in the string.
Python docs for match method state

Try to apply the pattern at the start of the string, returning
a match object, or None if no match was found.

import re
# read value from keyboard
value = input("Enter a string\n")
# match the entered value to be a number
result = re.match("[-+]?\d+$", value)
# check if there was a match
if result is not None:
    print("Entered string is an integer")
else:
    # entered value contains letters also
    print("Entered string is not an integer")

Output of above code is

Enter a string
-23
Entered string is an integer
Enter a string
codippa
Entered string is not an integer

Test negative values
If you want to test for strings containing negative integer values using isdigit or isnumeric functions, then strip off the first character using lstrip function as shown below.

str = '-123'
if str.lstrip("-").isnumeric():
   print('Integer value')
else:
   print('Not an integer')

lstrip will remove the given characters from the left of string and return a new string with the characters removed.
Hope the article was useful. Do not forget to hit the clap button.

Leave a Reply