How to Check If a Python String Can Convert to an Integer
Check whether a Python string is a valid integer using int(), try and except, or string methods, including signs and surrounding whitespace.
The most reliable way to check whether a Python string can convert to an integer is to call int() inside a try and except block.
def can_convert_to_int(value: str) -> bool:
try:
int(value)
except (TypeError, ValueError):
return False
return True
print(can_convert_to_int("42")) # True
print(can_convert_to_int("-42")) # True
print(can_convert_to_int("3.14")) # False
This tests the conversion you intend to perform, so it handles signs and whitespace correctly.
Convert and validate at the same time
If you need the converted value, avoid validating and then converting in two separate steps:
raw_value = " -42 "
try:
number = int(raw_value)
except ValueError:
print("Enter a whole number")
else:
print(number) # -42
The else block runs only when conversion succeeds.
Why str.isdigit() is not always enough
isdigit() is convenient when a value must contain only digit characters:
"42".isdigit() # True
"-42".isdigit() # False
" 42 ".isdigit() # False
It rejects a leading sign and surrounding whitespace, even though int() accepts those strings. Use isdigit() for deliberately strict digit-only input and int() when the question is whether Python can convert the value.
Check without using exceptions
For ASCII integers with an optional sign, remove whitespace and inspect the remaining characters:
def is_ascii_integer(value: str) -> bool:
value = value.strip()
if value.startswith(("+", "-")):
value = value[1:]
return bool(value) and value.isascii() and value.isdigit()
The bool(value) check prevents an empty string or a sign by itself from being accepted.
Common edge cases
| Input | Conversion succeeds? | Notes |
|---|---|---|
"42" | Yes | Ordinary integer |
"-42" | Yes | Negative integer |
"+42" | Yes | Explicit positive sign |
" 42 " | Yes | Whitespace is ignored |
"3.0" | No | Decimal string |
"1,000" | No | Separators need separate handling |
"" | No | Empty string |
None | No | Raises TypeError |
Do not convert a decimal string with int(float(value)) unless truncating the decimal portion is explicitly intended.
Validate values from forms and CSV files
Conversion and business validation are separate steps:
def parse_quantity(raw_value: str) -> int:
try:
quantity = int(raw_value)
except (TypeError, ValueError) as error:
raise ValueError("Quantity must be a whole number") from error
if quantity < 0:
raise ValueError("Quantity cannot be negative")
return quantity
Quick reference
- Use
int()withtry/exceptfor the most accurate test. - Catch
ValueError, and alsoTypeErrorifNoneis possible. - Use
isdigit()only when signs and whitespace must be rejected. - Convert once and retain the result rather than checking and converting twice.
Next, see how to convert every item in a list to integers.