HOWTO · Python
How to Check if a String Is Integer in Python
This tutorial explains how we can check if a string is an integer or not in Python.
On this page
To check whether Python can parse a string as an integer, call int() and handle ValueError. This accepts signed values and surrounding whitespace according to Python’s integer conversion rules. If your input must follow a narrower text format, use str.isdigit() for digits only or a regular expression for an explicitly defined format. These checks answer different questions: parseability versus matching a particular spelling.
Check whether a string represents an integer with int()
The most direct test is to try converting the value with int(). A successful conversion means the text is accepted by Python’s integer parser; catch ValueError when it is not. This approach accepts strings such as "+12", "-12", and " 12 ", so it is useful when those forms are valid for your application.
Run this example:
value = "42"
number = int(value)
print(number)
A reusable predicate can return a Boolean, but this function does not retain the parsed number: it discards the result of int(value).
def is_integer_text(value):
try:
int(value)
except ValueError:
return False
return True
for value in ("123", "-456", "abc", ""):
print(f"{value!r}: {is_integer_text(value)}")
Catch ValueError, which is the conversion failure for ordinary non-integer text. If the input can be something other than a string, validate its type separately; int() also accepts some non-string values, and the predicate’s intended input here is text. Conversion can accept whitespace around digits, so strip or reject whitespace first if your input format forbids it.
Check digit-only strings with str.isdigit()
Use str.isdigit() when the rule is specifically that every character is a digit and at least one character is present. It returns False for an empty string and for a leading plus or minus sign. This makes it a useful simple format check, but it is narrower than asking whether int() can parse the string. Some Unicode digit characters also satisfy isdigit(), so use an ASCII-specific rule if your format requires only 0 through 9.
def has_only_digits(value):
return value.isdigit()
for value in ("132", "-132", "", "12a"):
print(f"{value!r}: {has_only_digits(value)}")
There is no need to inspect value[0] to handle a sign. That would need a length check, and a separate sign rule still must ensure that digits follow it. For signed integer text, prefer the int() approach; if a fixed spelling is required, define that format directly with a regular expression.
Use a regular expression for a specific integer format
A regular expression is appropriate when the accepted spelling is part of your input contract. For example, r"[+-]?[0-9]+" describes an optional ASCII sign followed by one or more ASCII digits. Use fullmatch() so the entire string must follow the format; match() can accept a matching prefix and leave trailing characters unchecked.
import re
integer_format = re.compile(r"[+-]?[0-9]+")
for value in ("123", "+123", "-123", "12x", ""):
print(f"{value!r}: {integer_format.fullmatch(value) is not None}")
This pattern intentionally rejects surrounding whitespace and Unicode digits. Change it only to reflect the format you actually need. A regular expression verifies text shape; it does not convert the value or impose an application-specific numeric range. Convert a matched value with int() afterward if you need an integer object.
Choose the right approach
Choose int() inside try ... except ValueError when you want to know whether Python can parse the string as an integer. Choose str.isdigit() for a simple unsigned digit-only check. Choose re.fullmatch() when you need to enforce details such as ASCII digits, an optional sign, or the absence of whitespace. Avoid removing a sign with replace(): it can accept a sign in the wrong position and obscure the format rule.
The key distinction is that parsing and validation are not interchangeable. int() answers whether conversion works; str.isdigit() and a regular expression answer whether the original text matches a chosen character pattern. Select the rule that matches the input contract, then add a range check separately if the application limits the allowed integer values.