Checking String Representation of an Integer without Try/Except
Determining whether a given string represents an integer can prove tricky without resorting to exception handling. Here's how to navigate this challenge:
Using .isdigit() for Positive Integers
For positive integers, the .isdigit() method offers a straightforward solution:
'16'.isdigit() # True
Handling Negative Integers
Negative integers require a bit more effort. We can check if the string starts with a minus sign and verify that the remaining characters consist of digits:
s = '-17' s.startswith('-') and s[1:].isdigit() # True
Excluding Floating-Point Numbers
Unfortunately, this approach falls short when dealing with floating-point numbers. For a comprehensive solution, we can consider the following function:
def check_int(s): if s[0] in ('-', '+'): return s[1:].isdigit() return s.isdigit()
This function allows for both positive and negative integers while excluding floating-point numbers. For instance:
check_int('3.14') # False check_int('-7') # True
The above is the detailed content of How to Check 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!