Home > Backend Development > Python Tutorial > How to Check if a String Represents an Integer in Python Without Using Try/Except?

How to Check if a String Represents an Integer in Python Without Using Try/Except?

DDD
Release: 2024-12-11 02:52:10
Original
472 people have browsed it

How to Check if a String Represents an Integer in Python Without Using Try/Except?

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
Copy after login

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
Copy after login

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()
Copy after login

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
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template