Ad

Python - Find String Between Variable Number Of Substrings

I have a string which is [-0.0597212 0.00344087 -0.23413301 0.02406648]

As you see, there is [ at first, there are 3 spaces between 1st and 2nd value, 1 space between 2nd and 3rd value, 2 spaces between 3rd and 4th value, and there is ] at the end.

I want to decompose these 4 numerical values with their signs and I will assign these 4 values to an 4-element array.

For example;

a[0]=-0.0597212
a[1]=0.00344087
a[2]=-0.23413301
a[3]=0.02406648

Normally there will be 128 elements with like this text (there will be maximum 3 spaces, minimum 1 space between values), but I want to try to find the solution with this example. I tried split.strip() and replace() functions but I didn't find any solution for me. Can you help me ?

Ad

Answer

a="[-0.0597212   0.00344087 -0.23413301  0.02406648]"

#split string
a = a.split() 

#delete open & close square bracket
a[0] =  a[0][1:] 
a[-1] = a[-1][:-1] 

#convert to float
for i in range(len(a)):
    a[i] = float(a[i])
Ad
source: stackoverflow.com
Ad