ATidedHumour
ATidedHumour

Reputation: 193

How to convert a string looking like a list to list of floats?

I have this list:

s = '[ 0.00889175 -0.04808848  0.06218296 0.06312469 -0.00700571\n -0.08287739]'

it contains a '\n' character, I want to convert it to a list of float like this:

l = [0.00889175, -0.04808848, 0.06218296, 0.06312469, -0.00700571, -0.08287739]

I tried this code, which is close to what I want:

l = [x.replace('\n','').strip(' []') for x in s.split(',')]

but it still keeps quotes that I didn't manage to remove (i tried str.replace("'","") but it didn't work), this is what I get:

['0.00889175 -0.04808848  0.06218296 0.06312469 -0.00700571 -0.08287739']

Upvotes: 0

Views: 71

Answers (2)

Azeem
Azeem

Reputation: 302

First thing needs to cleared that if you are keeping the str then there will be quotes unless you typecast each of element of your str by splitting it.

Following is my solution to your problem:

s='[ 0.00889175 -0.04808848  0.06218296 0.06312469 -0.00700571\n -0.08287739]'

#removing newline \n
new_str = s.replace('\n', '')

#stripping the brackets and extra space
new_str = new_str.strip(' []')

#splitting elements into a list
list_of_floats = new_str.split()

#typecasting from str to float
for _i, element in enumerate(list_of_floats):
    list_of_floats[_i] = float(element)

print(list_of_floats)

#output
#[0.00889175, -0.04808848, 0.06218296, 0.06312469, -0.00700571, -0.08287739]

Upvotes: 2

ruohola
ruohola

Reputation: 24137

You were quite close. This will work:

s = '[ 0.00889175 -0.04808848  0.06218296 0.06312469 -0.00700571\n -0.08287739]'

l = [float(n) for n in s.strip("[]").split()]

print(l)

Output:

[0.00889175, -0.04808848, 0.06218296, 0.06312469, -0.00700571, -0.08287739]

Upvotes: 6

Related Questions