How to check if a string is an integer in python / Various ways to check for a numeric string 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. If the string is not integer then the conversion process will fail resulting in code break. Example, 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.


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.


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.


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.

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!!!

Mark Your Impression

Close Menu