Python error: could not convert string to float

17,209

Solution 1

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]

Solution 2

You may do the following to convert your string that you read from your file to a list of float

>>> instr="[2.467188005806714e-05, 0.18664554919828535, 0.5026880460053854]"
>>> [float(e) for e in instr.strip("[] \n").split(",")]
[2.467188005806714e-05, 0.18664554919828535, 0.5026880460053854]

The reason your code is failing is, you are not stripping of the '[' from the string.

Solution 3

You are capturing the first bracket, change string.index("[") to string.index("[") + 1

Solution 4

This will give you a list of floats without the need for extra imports etc.

s = '[2.467188005806714e-05, 0.18664554919828535, 0.5026880460053854]'
s = s[1:-1]
float_list = [float(n) for n in s.split(',')]


[2.467188005806714e-05, 0.18664554919828535, 0.5026880460053854]
Share:
17,209
chrizz
Author by

chrizz

Updated on June 18, 2022

Comments

  • chrizz
    chrizz almost 2 years

    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?

  • Steven Rumbalski
    Steven Rumbalski about 12 years
    If json.loads or ast.literal_eval did not exist, this would be the best way to accomplish the task.
  • Aaron Dufour
    Aaron Dufour about 12 years
    @Akavall eval is unsafe because it will evaluate arbitrary code. literal_eval will only evaluate certain data structure code, such as lists, dicts, bools, and None.
  • Akavall
    Akavall about 12 years
    @AaronDufour, I see. Thank You.