To convert a string to a float, one can use the python built-in function called float(), example:
>>> s = '3.1415'
>>> type(s)
<class 'str'>
>>> s = float(s)
>>> type(s)
<class 'float'>
However, if the string variable can't be converted to float, the following error message appears:
ValueError: could not convert string to float:
To avoid that, we can process as below:
>>> try:
... float(s)
... print('True')
... except:
... print('False')
...
3.1415
True
or create a simple function:
>>> def check_string_to_float(s):
... try:
... float(s)
... print('True')
... except:
... print('False')
example:
>>> s = '3.1415...'
>>> check_string_to_float(s)
False
Note: if the string uses commas instead of points, we can use the function replace():
>>> s = '3,1415'
>>> check_string_to_float(s)
False
>>> check_string_to_float(s.replace(',','.'))
True
Another example:
>>> s = 'abcd'
>>> check_string_to_float(s)
False
References
Liens | Site |
---|---|
float() | python doc |
Fast checking if a string can be converted to float or int in python | stackoverflow |
Checking if a string can be converted to float in Python | stackoverflow |
Python parse comma-separated number into int | stackoverflow |