Check if a String is a Number / Float in Python

This article will discuss two different ways to check if a given string contains a number or float only.

Table of contents

Use Regex to check if a string contains only a number/float in Python

In Python, the regex module provides a function regex.search(), which accepts a pattern and a string as arguments. Then it looks for the pattern in the given string. If a match is found, it returns a Match object; otherwise returns None. We will use this regex.search() function to check if a string contains a float or not. For that we will use the regex pattern “[-+]?\d*.?\d+(?:[eE][-+]?\d+)?$”. This pattern validates the following points in a string,

  • The string must start with a decimal or a symbol i.e. plus or minus.
  • After first symbol, there can be digits and then an optional dot and then again some digits.
  • The string must end with digits only.
  • Also, there can be an exponent symbol i.e. either ‘e’ or ‘E’.

Let’s create a function that will use the above-mentioned regex pattern to check if the given string contains a number or float only,

import re    

def is_number_or_float(sample_str):
    ''' Returns True if the string contains only
        number or float '''
    result = True
    if re.search("[-+]?\d*\.?\d+(?:[eE][-+]?\d+)?$", sample_str) is None:
        result = False
    return result

Now we will test this function with different types of strings to validate that it identifies the string representation of numbers and floats.

Advertisements

For example,

print( is_number_or_float("56.453") )
print( is_number_or_float("-134.2454") )
print( is_number_or_float("454") )
print( is_number_or_float("-1454.7") )
print( is_number_or_float("0.1") )
print( is_number_or_float("abc134.2454edf") )
print( is_number_or_float("abc") )

Output:

True
True
True
True
True
False
False

Analysis of the returned values,

  • It returned True for “56.453” because it contains only digits and a dot.
  • It returned True for “-134.2454” because it contains a minus symbol and digits and a dot.
  • It returned True for “454” because it contains only digits.
  • It returned True for “-1454.7” because it contains a minus symbol, digits and a dot.
  • It returned True for “0.1” because it contains a dot and digits
  • It returned False for “abc134.2454edf” because it contains some alphabets too.
  • It returned False for “abc” because it contains some alphabets too.

This proves that our function can check if the given string contains a number or float only.

Use Exceptional handling to check if a string contains only a number/float

We can pass the given string to the float() function. If string contains the correct representation of a number or float then it returns the float value, otherwise it raises a ValueError. We can catch this error and validate if string is float. We have created a function that will use the exception handling and float() function to check if given string object contains a float only,

def is_number(sample_str):
    """ Returns True if string contains only a
        number or float """
    result = True
    try:
        float(sample_str)
    except:
        result = False
    return result

Now we will test this function with different types of strings to validate that it identifies the string representation of numbers and floats.

For example,

print( is_number("56.453") )
print( is_number("-134.2454") )
print( is_number("454") )
print( is_number("-1454.7") )
print( is_number("0.1") )
print( is_number("abc134.2454edf") )
print( is_number("abc") )

Output:

True
True
True
True
True
False
False

Analysis of the returned values,

  • It returned True for “56.453” because it contains only digits and a dot.
  • It returned True for “-134.2454” because it contains a minus symbol and digits and a dot.
  • It returned True for “454” because it contains only digits.
  • It returned True for “-1454.7” because it contains a minus symbol, digits and a dot.
  • It returned True for “0.1” because it contains a dot and digits
  • It returned False for “abc134.2454edf” because it contains some alphabets too.
  • It returned False for “abc” because it contains some alphabets too.

This proves that our function can check if the given string contains a number or float only.

The complete example is as follows,

print("********** Using Regex **********")

import re    

def is_number_or_float(sample_str):
    """ Returns True if string contains only a
        number or float """
    result = True
    if re.search("[-+]?\d*\.?\d+(?:[eE][-+]?\d+)?$", sample_str) is None:
        result = False
    return result

print( is_number_or_float("56.453") )
print( is_number_or_float("-134.2454") )
print( is_number_or_float("454") )
print( is_number_or_float("-1454.7") )
print( is_number_or_float("0.1") )
print( is_number_or_float("abc134.2454edf") )
print( is_number_or_float("abc") )

print("********** Using Exception Handling **********")

def is_number(sample_str):
    """ Returns True if string contains only a
        number or float """
    result = True
    try:
        float(sample_str)
    except:
        result = False
    return result


print( is_number("56.453") )
print( is_number("-134.2454") )
print( is_number("454") )
print( is_number("-1454.7") )
print( is_number("0.1") )
print( is_number("abc134.2454edf") )
print( is_number("abc") )

Output:

********** Using Regex **********
True
True
True
True
True
False
False
********** Using Exception Handling **********
True
True
True
True
True
False
False

Summary:

We learned how to check if a string contains a number or a float only.

Pandas Tutorials -Learn Data Analysis with Python

   

Are you looking to make a career in Data Science with Python?

Data Science is the future, and the future is here now. Data Scientists are now the most sought-after professionals today. To become a good Data Scientist or to make a career switch in Data Science one must possess the right skill set. We have curated a list of Best Professional Certificate in Data Science with Python. These courses will teach you the programming tools for Data Science like Pandas, NumPy, Matplotlib, Seaborn and how to use these libraries to implement Machine learning models.

Checkout the Detailed Review of Best Professional Certificate in Data Science with Python.

Remember, Data Science requires a lot of patience, persistence, and practice. So, start learning today.

Join a LinkedIn Community of Python Developers

Leave a Comment

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top