-4

I have a text file that I am trying to read and receive string with brackets and convert it into a float array.

The text file reads as:

[0.1, 0.4242230677806444] 

and the string I read from the text file using the following scripts:

testsite_array = []
with open('BestIndividuals_Gen.txt') as my_file:
    for line in my_file:
        testsite_array.append(line)

gives a string like "[0.1, 0.4242230677806444]" but how can I convert this string with brackets into float array?

Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
Ning An
  • 21
  • 1
  • It's valid JSON (!?), so you could `json.load` it… – deceze Jul 27 '20 at 07:17
  • Try `ast.literal_eval()` – bigbounty Jul 27 '20 at 07:19
  • 1
    On a second look, you are misleading. You don't really get a string representation of a list. You have an actual list that you add strings to. You can just convert them to floats by doing `testsite_array.append(float(line.strip()))` – Tomerikoo Jul 27 '20 at 07:29

1 Answers1

1

You can do this in two steps.

string_array = "[0.1, 0.4242230677806444]"
# Step one convert to string array
as_array = string_array.strip('][').split(', ')
# Step two convert string array to float
as_float_array = [float(x) for x in  as_array]

Alternatively you can use the library ast

import ast 
string_array = "[0.1, 0.4242230677806444]"
as_float_array  = ast.literal_eval(string_array) 

See also: https://www.geeksforgeeks.org/python-convert-a-string-representation-of-list-into-list/