5

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?

1
  • 7
    Do you see the [ in your error message? Commented Apr 16, 2012 at 14:53

5 Answers 5

16

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]
Sign up to request clarification or add additional context in comments.

1 Comment

@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.
5

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.

1 Comment

If json.loads or ast.literal_eval did not exist, this would be the best way to accomplish the task.
3

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

Comments

1

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]

Comments

0
v = string[string.index('[') + 1:].split(',')

index() return index of given character, so that '[' is included in sequence returned by [:].

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.