How to check whether a string is integer in python

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.
[the_ad id=”651″] 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.
[the_ad id=”656″] 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.
[the_ad id=”89″] 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

[AdSense-A] 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.
[AdSense-B] Hope the article was useful. Do not forget to hit the clap button.

How to check if a string is an integer in python

Often it is required to convert a string to an integer but before conversion it is recommended to check if the string being converted is in integer format or not.
This might be useful when converting a user input value into an integer since user entered value will always be a string.
If the string is not integer then the conversion process will fail resulting in code break. This is because it is possible to convert “12” into 12 but trying to convert ‘twelve’ into a integer will result in an error.
This post shall list down different methods by which we can check a string to be compatible format before conversion.
[the_ad id=”651″] Method 1: Using isdigit function
Python provides an in-built function isdigit which takes a string as an argument and returns True if the argument is a positive integer, False otherwise.

# read value from keyboard
value = input("Enter a string\n")
# check if value is integer
if value.isdigit():
    print("Entered string is an integer")
else:
    print("Entered string is not an integer")

Enter a string
12
Entered string is an integer
Enter a string
five
Entered string is not an integer

Note that isdigit will return True for positive integers only. For negative integers or those preceded with plus sign, you need to remove the preceding + and – using lstrip function as value.lstrip("-+").isdigit(). But still, this method can not be used to test decimal values.
[the_ad id=”656″] Method 2: Using try/except block
Use int function inside a try block enclose with an except block catching ValueError. If the string is successfully converted, the code following int statement will be executed else the control will jump to except block.
Note than int function takes a string as argument and returns its integer equivalent.

# read value from keyboard
value = input("Enter a string\n")
try:
    # convert entered value to integer
    int(value)
    print("Entered string is an integer")
except ValueError:
    # entered value cannot be converted to integer
    print("Entered string is not an integer")

Below are sample runs of this program

Enter a string
-12
Entered string is numeric
Enter a string
five
Entered string is not an integer

Note that this method can handle strings preceded with + and – signs and no extra code is required unlike the first method but it can not handle decimal values.

[the_ad id=”647″] Method 3: 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")

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

Regular expression [-+]?\d+$ can be broken up as
[-+]? checks if the string starts with -, + or without both. ? at the end checks if 0 or 1 of the first character of entered string matches + or -. If you do not want to check for negative strings, this expression can be omitted.
\d+ matches for 1 or more digits.
$ at the end enforces that the string contains numbers only. It checks the string contains only the expression before it(that is, numbers only).This is required to avoid strings such as 23d3, 4dsd3 etc.
[AdSense-A] In place of \d+, you can also use [0-9]+ which means one or more values between 0-9. Thus, the modified regular expression becomes [-+]?[0-9]+$
That was all about methods to check if an input string is an integer in python. Keep visiting!!!

Categorized in:

Python,
Exit mobile version