5 ways to check if a string is an integer in Python [Practical Examples]

How to check if a string is an integer in Python

When operating with numbers and strings, many times while fetching the data from the text box, we fetch it as a string. Now, on back-end this data may be stored as a number. Hence, before converting a string to integer it is mandatory to check if a string contains an integer value or not. Otherwise, it will throw a ValueError exception. There are five different ways to check if a string is an integer in python.

  1. Using isdecimal() function
  2. Using isdigit() function
  3. Using isnumeric() function
  4. Using Regular expression function
  5. Using ValueError Exception

 

Method-1: Using isdecimal() function to check if a string is an integer

The isdecimal() is a method used to check if a string is an integer or not. It returns True if all characters in the string are digits and, False otherwise. Decimal characters are those that can be used to form numbers in base 10. In other words, isdecimal() function only supports decimal numbers.
The syntax of isdecimal() method is as shown below. Here, st is a string.

Advertisement
st.isdecimal()

 

Example 1 In this example, we will take one string containing number and other containing combination of numbers and alphabets.

# Initializing the string with number and alpha numeric values
s1="112"
s2="22aa"

# Using isdecimal to check and print the results
print("Is string ", s1, "a number?",s1.isdecimal())
print("Is string ", s2, "a number?",s2.isdecimal())    

Output

Is string  112 a number? True
Is string  22aa a number? False

 

Example 2 In this example, we will take input from the user.

# Initializing the string with number and alpha numeric values
s1=input("Enter a number")

# Using isdecimal to check and print the results
print("Is string ", s1, "a number?",s1.isdecimal())
print("Is string ", s2, "a number?",s2.isdecimal())    

Output

Enter a number
225
Is string  225 a number? True

 

Method-2: Using isdigit() function to check if a string is an integer

The isdigit() is a method used to check if a string is an integer or not. It returns True if all characters in the string are digits and, False otherwise. Digits may be a decimal characters and digits that need special handling, such as the compatibility superscript digits. In other words, isdigit() function also supports Subscripts, Superscripts in addition to decimal numbers. This makes it different from isdecimal() function.

The syntax of isdigit() method is as shown below. Here, st is a string.

Advertisement
st.isdigit()

 

Example 1 In this example, we will take one string containing number and other containing combination of numbers and alphabets.

# Initializing the string with number and alpha numeric values
s1="112"
s2="22aa"

# Using isdigit to check and print the results
print("Is string ", s1, "a number?",s1.isdigit())
print("Is string ", s2, "a number?",s2.isdigit())    

Output

Is string  112 a number? True
Is string  22aa a number? False

 

Example 2 In this example, we will take input from the user.

# Initializing the string with number and alpha numeric values
s1=input("Enter a number")

# Using isdigit to check and print the results
print("Is string ", s1, "a number?",s1.isdigit())
print("Is string ", s2, "a number?",s2.isdigit())    

Output

Enter a number
225
Is string  225 a number? True

 

Method-3: Using isnumeric() function to check if a string is an integer

The isnumeric() function returns True if all characters in the string are numeric characters, and there is at least one character, False otherwise. Numeric characters include digit characters, and all characters that have the Unicode numeric value property. In other words, isnumeric supports numeric values and equivalent Unicode characters of roman numerals, superscripts, subscripts and fractions. The syntax of isnumeric() method is as shown below. Here, path is a file name or absolute path.

str.isnumeric()

 

Example 1 In this example, we will take different Unicode characters for a vulgar function half and quarter to verify the results.

s = '449'
print(s,"-", s.isnumeric())
 
# Unicode character for vulgar function 1/2
s = '\u00BD'
print(s,"-", s.isnumeric())

# Unicode character for vulgar function 1/4
s = '\u00BC'
print(s,"-", s.isnumeric())

s='\u00A3'
print(s,"-", s.isnumeric())

Output

449 - True
½ - True
¼ - True
£ - False

 

Method-4: Using Regular expression function to check if a string is an integer

Regular expressions are the search pattern or a predefined sequence of characters that makes it possible to match or find the occurrence of a string. In this approach, we will use match() method of a regular expression to check if a string is an integer or not. The syntax of match is as shown below. Here, pattern contains regular expression to be matched. String contains the input that we are matching whereas flag are optional modifiers. This approach is suitable if we are not sure that results will only contain positive numbers.

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

This method will return the matched objects if found and None otherwise.

 

Example 1 In this example, we will take regular expression to specify that number can be positive or negative.

# Import module for regular expression
import re

# Getting input from the user
s = input("Enter any value: ")

# Using match function to check for positive and negative integer numbers
r = re.match("[-+]?\d+$", s)

# Printing the results
if r is None:
    print("Given string is not an Integer")
else:
    print("Given string is an Integer")

Output

Enter any value: 588
Given string is an Integer

 

Method-5: Using ValueError Exception

This is a very logical but simple approach. We know that Python will raise Valueerror exception if we try to convert string containing non numeric characters to a number. So, we will use this mechanism to check if a string is an integer or not.

 

Example 1 In this example, we will use try and except block and will throw an ValueError exception if the given string cannot be converted to the integer.

# Initializing a string
s = 'aa221'

# Initializing flag with True value
flag = True

# Check if a string is an integer or not
try:
   # Trying to convert it to integer
   int(s)
# Handling exception
except ValueError:
   flag = False

# Printing the results
if flag:
   print("Given string is an integer")
else:
   print('Given string is not an integer')

Output

Given string is not an integer

 

Summary

The knowledge of checking if the string is an integer or not is important if we are working on the form data in real time applications. While fetching the values from the user form, it is retrieved in the form of string. Thereafter, certain form fields requires validation before we store it in database. In this tutorial, we covered the five different ways to check if a string is an integer or not with an example. All in all, this tutorial, covers everything that you need to know in order to check if a string is an integer in Python.

 

References

Python stdtypes

Advertisement

 

Didn't find what you were looking for? Perform a quick search across GoLinuxCloud

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can either use the comments section or contact me form.

Thank You for your support!!

Leave a Comment

X