String to float conversion with python

Published: 23 mars 2018

DMCA.com Protection Status

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