How to Check if a String is an Integer or Float in Python?

In this tutorial, I will explain how to check if a string is an integer or float in Python. As a Python developer working on a project for one of my clients in New York, I came across a situation when dealing with user input and data parsing, I needed to check if a string is an integer or float. Let’s get into the details with examples and screenshots of executed example code.

Methods to Check if a String is an Integer in Python

Python provides various methods to check if a string is an integer. Let us see some important methods.

Method 1. Use the isdigit() Method

The isdigit() method is a built-in Python string method that returns True if all characters in the string are digits and there is at least one character otherwise, it returns False.

def is_integer(s):
    return s.isdigit()

# Example
input_string = "12345"
print(is_integer(input_string))

input_string = "12345.67"
print(is_integer(input_string)) 

Output:

True
False

I have executed the above example code and added the screenshot below.

String is an Integer or Float in Python

Read How to Remove Numbers from Strings in Python?

Method 2. Use the int() Function with Exception Handling

Another approach is to use the int() function to attempt to convert the string to an integer. If the conversion fails, a ValueError is raised, which we can catch and handle.

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

# Example
input_string = "67890"
print(is_integer(input_string)) 

input_string = "67890.12"
print(is_integer(input_string))

Output:

True
False

I have executed the above example code and added the screenshot below.

Check if a String is an Integer or Float in Python

Check out Difference Between Functions and Methods in Python

Method 3. Use Regular Expressions

Regular expressions provide a powerful way to validate strings. The re module in Python can be used to check if a string contains only digits.

import re

def is_integer(s):
    return bool(re.match(r"^\d+$", s))

# Example
input_string = "54321"
print(is_integer(input_string)) 

input_string = "54321.89"
print(is_integer(input_string)) 

Output:

True
False

I have executed the above example code and added the screenshot below.

How to Check if a String is an Integer or Float in Python

Read How to Use the insert() Function in Python?

Methods to Check if a String is a Float in Python

Let us see some important methods to check if a string is a float in Python.

Method 1. Use the float() Function with Exception Handling

Similar to checking for integers, you can use the float() function to attempt to convert the string to a float.

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

# Example
input_string = "12345.67"
print(is_float(input_string))

input_string = "12345"
print(is_float(input_string))

input_string = "12345.67.89"
print(is_float(input_string))

Output:

True
True
False

I have executed the above example code and added the screenshot below.

Check if a String is an Integer or Float in Python float() Function

Check out How to Use the arange() Function in Python?

Method 2. Use Regular Expressions

Regular expressions can also be used to validate if a string is a float. The pattern for a float includes an optional sign, digits, and an optional decimal point followed by digits.

import re

def is_float(s):
    return bool(re.match(r"^[+-]?(\d+(\.\d*)?|\.\d+)$", s))

# Example
input_string = "67890.12"
print(is_float(input_string)) 

input_string = "67890"
print(is_float(input_string))

input_string = "67890.12.34"
print(is_float(input_string))

Output:

True
True
False

Check out How to Use the Python Pass Function?

Combine Checks for Integer and Float

In some cases, you may want to check if a string is either an integer or a float. You can combine the methods described above to create a comprehensive function.

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

# Example
input_string = "12345"
print(is_number(input_string)) 

input_string = "12345.67"
print(is_number(input_string))

input_string = "12345.67.89"
print(is_number(input_string))

Output:

True
True
False

Read Should I Learn Java or Python?

Examples

Let us see some real-world scenarios to understand more about the topic.

Example 1: Validate User Input in a Financial Application

Think you’re developing a financial application where users input their annual income and tax rates. You need to ensure that these inputs are numeric values.

def validate_financial_input(income, tax_rate):
    if not is_number(income):
        return "Invalid income input. Please enter a numeric value."
    if not is_number(tax_rate):
        return "Invalid tax rate input. Please enter a numeric value."
    return "Inputs are valid."

# Example
income = "50000"
tax_rate = "7.5"
print(validate_financial_input(income, tax_rate)) 

income = "50k"
tax_rate = "7.5"
print(validate_financial_input(income, tax_rate))  

Output:

 Inputs are valid.
Invalid income input. Please enter a numeric value.

Read Difference Between {} and [] in Python

Example 2: Parse Data from a CSV File

Consider a scenario where you’re parsing a CSV file containing product prices. You need to ensure that the prices are valid floats.

import csv

def validate_prices(file_path):
    with open(file_path, mode='r') as file:
        csv_reader = csv.reader(file)
        for row in csv_reader:
            product_name, price = row
            if not is_float(price):
                print(f"Invalid price for product {product_name}: {price}")
            else:
                print(f"Valid price for product {product_name}: {price}")

# Example CSV content:
# Apple,1.25
# Banana,0.75
# Cherry,invalid_price

validate_prices('products.csv')

Read Difference Between “is None” and “== None” in Python

Conclusion

In this tutorial, we explored various methods to check if a string is an integer or float in Python. By using built-in methods like isdigit(), exception handling with int() and float(), and regular expressions, you can effectively validate numeric strings in Python. We used exception handling with float() function , using regular expressions. I combined checks for integers and float with real-world examples.

You may also like to read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.