How can I check if a string represents an int, without using try/except?
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
Introduction
Python offers several ways to check if a string represents an integer without try/except: str.isdigit() for non-negative integers, str.lstrip('+-').isdigit() for signed integers, and re.fullmatch() for full regex validation. While try/except with int() is the most Pythonic (EAFP) approach, there are valid reasons to avoid it — performance in tight loops, avoiding exception-driven control flow, or pre-validating user input before processing. This article covers all non-exception approaches.
Method 1: str.isdigit()
isdigit() returns True only if all characters are digits and the string is non-empty. It does not handle negative numbers, leading + signs, or whitespace.
Method 2: Handle Signed Integers
Strip whitespace first, then check if the first character is a sign. After removing the optional sign, verify the rest contains only digits.
Method 3: Regular Expression
re.fullmatch() validates the entire string against the pattern. Pre-compile the regex with re.compile() when checking many strings.
Method 4: str.isnumeric() and str.isdecimal()
isdecimal() is the strictest — it only matches characters that represent decimal digits. isdigit() also matches superscripts. isnumeric() is the broadest, matching fractions and Roman numerals in Unicode.
Method 5: Custom Character Check
Performance Comparison
str.isdigit() is the fastest for simple non-negative checks. For mixed valid/invalid data, string methods outperform try/except because exception handling has overhead on failure.
Common Pitfalls
isdigit()returnsTruefor Unicode superscripts:"²".isdigit()returnsTrue, butint("²")raisesValueError. Useisdecimal()for strict ASCII digit validation.- Empty string returns
Falsebut bare sign doesn't: Both"".isdigit()and"-".lstrip('-').isdigit()returnFalse, but you should explicitly handle these edge cases for clarity. - Leading/trailing whitespace:
" 42 ".isdigit()returnsFalsebecause spaces are not digits. Always call.strip()first if your input might contain whitespace. - No support for other integer formats: None of these methods handle hex (
0xFF), octal (0o77), or binary (0b1010). Use regex or a custom parser for these. - Forgetting that
int()accepts more than digits:int(" -42 ")works fine with whitespace and signs. The string-method approach requires you to handle these manually, which adds complexity.
Summary
str.isdigit()— fast check for non-negative integers (digits only)str.lstrip('+-').isdigit()— quick signed integer checkre.fullmatch(r'[+-]?\d+', s)— regex for complete validationstr.isdecimal()— strictest string method (no Unicode superscripts)- Always
.strip()input before checking to handle whitespace - Pre-compile regex patterns when validating many strings in a loop

