Verifying Integer Strings Without Try/Except
When working with strings, it's often necessary to determine if a string represents an integer. Traditionally, this has been achieved using a try/except mechanism to attempt integer conversion and handle exceptions if it fails. However, there are alternative approaches that avoid the overhead of exception handling.
isdigit for Positive Integers
For positive integers, the Python function .isdigit() can be employed. It returns True if the string consists solely of digits and False otherwise:
>>> '16'.isdigit() True
Negative Integers with Prefix Check
This approach doesn't work for negative integers. To handle them, you can check for a hyphen prefix and then test if the remaining characters are digits:
>>> s = '-17' >>> s.startswith('-') and s[1:].isdigit() True
Handling Decimal Points
The above method falls short when handling strings containing decimal points. To address this, a slightly more complex approach is needed:
def check_int(s): if s[0] in ('-', '+'): return s[1:].isdigit() return s.isdigit()
This function checks for a positive or negative prefix and then uses .isdigit() to validate the remaining characters.
The above is the detailed content of How Can I Verify if a String Represents an Integer in Python Without Using Try/Except?. For more information, please follow other related articles on the PHP Chinese website!