Testing whether a Python string contains an integer

If you want to check whether a Python string is an integer, you can try casting to an int with int() and catching the ValueError if it’s not an integer:

1
2
3
4
5
6
def is_integer(value: str, *, base: int=10) -> bool:
    try:
        int(value, base=base)
        return True
    except ValueError:
        return False

To check for nonnegative integers, you can use the str.is_digit() method. It will “return true if all characters in the string are digits and there is at least one character, false otherwise:

1
2
3
4
>>> "123".isdigit()
True
>>> "-123".isdigit()
False

Thanks to Jeremy Kahn for reminding me that isdigit only detects positive integers.

Last updated on Feb 15, 2024 09:00 -0500
Feedback
FOOTER