Check if a String Is Integer in Python

Muhammad Waiz Khan Jan 30, 2023 Jan 28, 2021
  1. Check if a String Is Integer in Python Using the str.isdigit() Method
  2. Check if a String Is Integer in Python Using the try ... except Exception Handling
  3. Check if a String Is Integer in Python Using Regular Expression
Check if a String Is Integer in Python

This tutorial will explain how to check if a string is an integer or not in Python. By string being integer, we mean that the value stored in the string represents an integer. There can be multiple methods to check this, and we will discuss those methods with code examples in this tutorial.

Check if a String Is Integer in Python Using the str.isdigit() Method

The most efficient way to check if a string is an integer in Python is to use the str.isdigit() method, as it takes the least time to execute.

The str.isdigit() method returns True if the string represents an integer, otherwise False. The code example below shows how we can use it.

def if_integer(string):
  
    if string[0] == ('-', '+'):
        return string[1:].isdigit()

    else:
        return string.isdigit()

string1 = '132'
string2 = '-132'
string3 = 'abc'

print(if_integer(string1))
print(if_integer(string2))
print(if_integer(string3))

Output:

True
True
False

The above example also takes care if the sign of the integer, + or -, also exists in the string. If the first string is + or -, it checks if the rest of the string is an integer or not.

Check if a String Is Integer in Python Using the try ... except Exception Handling

Another method is to use try ... except exception handling on the int() function. If the string is an integer, it will return True and otherwise False. The code example below shows how we can implement this method.

def if_integer(string):
    try: 
        int(string)
        return True
    except ValueError:
        return False

string1 = '132'
string2 = '-132'
string3 = 'abc'

print(if_integer(string1))
print(if_integer(string2))
print(if_integer(string3))

Output:

True
True
False

Check if a String Is Integer in Python Using Regular Expression

A different and interesting approach we can use is the regular expression. The regular expression to represent an integer will be [+-]?\d+$, where [+-]? means that +- signs are optional, \d+ means there should be one or more digits in the string and $ is the end of the string.

Example code:

import re

def if_integer(string):

    reg_exp = "[-+]?\d+$"
    return re.match(reg_exp, string) is not None

string1 = '132'
string2 = '-132'
string3 = 'abc'

print(if_integer(string1))
print(if_integer(string2))
print(if_integer(string3)) 

Output:

True
True
False

Related Article - Python String

Related Article - Python Integer