Home »
Python
How do I check if a string is a number (float) in Python?
Example of float() method: Here, we are going to learn how do I check if a string is a number (float) in Python?
Submitted by Sapna Deraje Radhakrishna, on November 24, 2019
Using python it is very to interconvert the datatypes of a variable. A string can be easily converted to an integer or a float. However, asserting a string to be a float is a task by itself. Python provides an option to assert if a string is a float.
float()
Using the float() method, a variable can be type casted to a float variable. However, if the variable is not a valid float an exception is thrown.
Python 3.6.8 (default, Apr 25 2019, 21:02:35)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-36)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> test_string = "45.02"
>>> print("The original string is {}".format(test_string))
The original string is 45.02
>>> try:
... float(test_string)
... print("{} is a valid float variable".format(test_string))
... except:
... print("invalid float variable")
...
45.02
45.02 is a valid float variable
>>> test_string = "aa"
>>> try:
... float(test_string)
... print("{} is a valid float variable".format(test_string))
... except:
... print("invalid float variable")
...
invalid float variable