How can I check if a string represents an integer in Python, without using try/except?
For example, I want to verify if a string like ‘3’ or ‘-17’ is an integer, but strings like ‘3.14’ or ‘asfasfas’ should return False
. Here’s an example of the expected behavior:
is_int('3.14') == False
is_int('-7') == True
I’ve been working with Python for years, and when you need to verify if a string is an integer without using try/except
, one simple method is to use the str.isdigit()
function. This works perfectly for non-negative integers and is straightforward to implement:
string = "12345"
if string.isdigit():
print("It's an integer!")
else:
print("Not an integer.")
However, this doesn’t handle cases like negative integers or whitespace, so it’s more suitable for clean, positive numeric strings.
Building on Netra’s point, while str.isdigit()
is great for basic checks, you might encounter scenarios where you need to handle negative integers too. A more flexible approach is to use str.lstrip('-').isdigit()
. This method strips the leading -
and then checks if the rest is numeric:
string = "-12345"
if string.lstrip('-').isdigit():
print("It's an integer!")
else:
print("Not an integer.")
This method ensures that even negative numbers are caught accurately, but it might not cover cases like numbers with leading or trailing spaces.
Let’s refine this further. If you want a robust way to handle all cases—like strings with spaces, multiple -
signs, or empty strings—you can combine .strip()
and .isdigit()
intelligently. Alternatively, regular expressions provide a more comprehensive solution:
import re
def is_integer(string):
return bool(re.fullmatch(r"-?\d+", string.strip()))
# Examples
print(is_integer(" -12345 ")) # True
print(is_integer("123abc")) # False
This method handles leading/trailing whitespace, single negative signs, and strictly numeric strings, making it versatile and reliable.