Home »
Python
How do I check if a string is a number (float) in Python?
By Sapna Deraje Radhakrishna Last updated : December 21, 2024
Checking if a string is a number (float)
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.
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.
Example to check if a string is a number (float)
# Test with a valid float string
test_string = "45.02"
print("The original string is {}".format(test_string))
try:
float(test_string)
print("{} is a valid float variable".format(test_string))
except:
print("Invalid float variable")
# Test with an invalid float string
test_string = "aa"
try:
float(test_string)
print("{} is a valid float variable".format(test_string))
except:
print("Invalid float variable")
Output
The original string is 45.02
45.02 is a valid float variable
Invalid float variable