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 wrap the float
function call with a try-except block.
For instance, we write:
val = 'foobar'
try:
float(val)
except ValueError:
print("Not a float")
We call float
with val
to try to parse the string into a float.
This will raise a ValueError
exception since 'foobar'
isn’t a string with a floating point number.
Therefore, 'Not a float'
is printed since it’s caught by the except block.
Conclusion
To check if a string can be converted to float in Python, we can wrap the float
function call with a try-except block.