Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python error: could not convert string to float

I have some Python code that pulls strings out of a text file:

[2.467188005806714e-05, 0.18664554919828535, 0.5026880460053854, ....]

Python code:

v = string[string.index('['):].split(',')
for elem in v:
    new_list.append(float(elem))

This gives an error:

ValueError: could not convert string to float: [2.974717463860223e-06

Why can't [2.974717463860223e-06 be converted to a float?

like image 511
chrizz Avatar asked Apr 16 '12 14:04

chrizz


People also ask

Why can't I convert a string to a float in Python?

The Python "ValueError: could not convert string to float" occurs when we pass a string that cannot be converted to a float (e.g. an empty string or one containing characters) to the float() class. To solve the error, remove all unnecessary characters from the string.

Why can I not convert string to float?

This error usually occurs when you attempt to convert a string to a float in pandas, yet the string contains one or more of the following: Spaces. Commas. Special characters.

Can we convert string to float in Python?

We can convert a string to float in Python using the float() function. This is a built-in function used to convert an object to a floating point number.

What is a float in Python?

Float() is a method that returns a floating-point number for a provided number or string. Float() returns the value based on the argument or parameter value that is being passed to it. If no value or blank parameter is passed, it will return the values 0.0 as the floating-point output.


1 Answers

You've still got the [ in front of your "float" which prevents parsing.

Why not use a proper module for that? For example:

>>> a = "[2.467188005806714e-05, 0.18664554919828535, 0.5026880460053854]"
>>> import json
>>> b = json.loads(a)
>>> b
[2.467188005806714e-05, 0.18664554919828535, 0.5026880460053854]

or

>>> import ast
>>> b = ast.literal_eval(a)
>>> b
[2.467188005806714e-05, 0.18664554919828535, 0.5026880460053854]
like image 104
Tim Pietzcker Avatar answered Nov 15 '22 00:11

Tim Pietzcker