Skip to content

Python check if string is integer or float

  • by

You can use Python’s built-in functions and methods to check if a string represents an integer or a float. Here’s how you can do it:

Here’s the syntax for checking if a string represents an integer or a float in Python:

Check if the string represents an integer:

def is_integer(s):
    try:
        int(s)
        return True
    except ValueError:
        return False

Example:

def is_integer(s):
    try:
        int(s)
        return True
    except ValueError:
        return False

# Example usage:
print(is_integer("123"))  # Output: True
print(is_integer("3.14")) # Output: False
print(is_integer("abc"))  # Output: False

Check if the string represents a float:

def is_float(s):
    try:
        float(s)
        return True
    except ValueError:
        return False

Example:

def is_float(s):
    try:
        float(s)
        return True
    except ValueError:
        return False

# Example usage:
print(is_float("3.14"))  # Output: True
print(is_float("123"))   # Output: False
print(is_float("abc"))   # Output: False

These functions use try-except blocks to attempt to convert the input string to an integer or a float, respectively. If the conversion succeeds, the function returns True, indicating that the input is a valid integer or float. If the conversion raises a ValueError, it means the input is not a valid integer or float, and the function returns False.

Python checks if the string is an integer or float example

Let’s see an example to check if a string represents an integer or a float using the functions we defined earlier.

def is_integer(s):
    try:
        int(s)
        return True
    except ValueError:
        return False

def is_float(s):
    try:
        float(s)
        return True
    except ValueError:
        return False

# Example usage:
str1 = "123"
str2 = "3.14"
str3 = "abc"

print(f"{str1} is an integer: {is_integer(str1)}")
print(f"{str2} is an integer: {is_integer(str2)}")
print(f"{str3} is an integer: {is_integer(str3)}")

print(f"{str1} is a float: {is_float(str1)}")
print(f"{str2} is a float: {is_float(str2)}")
print(f"{str3} is a float: {is_float(str3)}")

Output:

Python check if string is integer or float

In the example above, we call the is_integer and is_float functions with different input strings to check if they represent an integer or a float, respectively. The functions return True if the input is a valid integer or float and False otherwise.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Your email address will not be published. Required fields are marked *