Learn How check if a string is a number in Python 3

In this tutorial we are going to learn how to check if a string is a number in Python 3 programming.

Python 3 has a built in string function called str.isnumeric() which will check whether a string is a numeric or not. But however str.isnumeric() function will return False for floating point number. To check if a string is a float, we can use try except statement.

Python is string numeric

Python str.isnumeric() function will return True if the given string is numeric or return False otherwise.

Example 1

print(str.isnumeric("10"))

The Above python code will return True, since “10” is a numeric value.

True

 

Example 2

print(str.isnumeric("abc"))

The Above python code will return False.

We can also use isnumeric() function with a string variable as follows.

number = "100"
print(number.isnumeric())

 

To be returned True, The whole string has to be numbers only or otherwise will return False. For Example.

number = "100A"
print(number.isnumeric())

Will return False since the variable number contains the letter "A".

Check if a string is a Float in Python 3

Python str.isnumeric() function will return False for the floating point numbers. But we can write a Simple function using try except statement to check whether a string is a floating point number or not.

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

As per the above python code, we created a new function called is_number(). The Function will simply try to convert the given string to a float and if the string can be converted to float, then the is_number function will return True.

Example

def is_number(string):
    try:
        float(string)
        return True
    except ValueError:
        return False
        
print(is_number("10.5"))

The Above Python Code will return True.

Summary

In this tutorial we learned how to check if a string is a number in python programming.

  • We used python str.isnumeric() function to check whether a string is a numeric or not.
  • To check Floating point numbers, we wrote a simple python function called is_number().