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.
Python’s exception handling mechanism can be used to test whether a string is an integer. Try to convert string to an integer using
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
If you want to check if a string is numeric without using exception handling or
try-exceptblock, then this method should be used.
Python’s inbuilt function
isnumericis invoked on a string and checks whether the string contains only numeric characters.
Trueif the string contains only integers and
Falseif it has any character other than numeric. Example,
str = '123' if str.isnumeric(): print('Integer value') else: print('Not an integer')
This method works the same as previous method and returns
Trueif the string contains only numeric digits and
str = '123' if str.isdigit(): print('Integer value') else: print('Not an integer')
This code will print
Method 4: Using regular expression
Regular expression can be used to check the presence of any character in a given string.
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.
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
Entered string is an integer
Enter a string
Entered string is not an integer
If you want to test for strings containing negative integer values using
isnumericfunctions, then strip off the first character using
lstripfunction 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.