Sometimes, we want to check if a string can be converted to float in Python.
In this article, we’ll look at how to check if a string can be converted to float in Python.
How to check if a string can be converted to float in Python?
To check if a string can be converted to float in Python, we can call float
in a try block.
For instance, we write
try:
float(element)
except ValueError:
print("Not a float")
to call float
with the value we want to check if the string can be converted to a float.
If it can’t be converted, then a ValueError
will be raised.
And we catch that with the except block.
Conclusion
To check if a string can be converted to float in Python, we can call float
in a try block.