简体   繁体   中英

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 ?

list(map(float, txt[1:-1].split()))
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])

If you use numpy() :

import numpy as np

s = '[-0.0597212   0.00344087 -0.23413301  0.02406648]'

np.fromstring(s.strip('[]'), dtype=float, sep=' ')
# [-0.0597212   0.00344087 -0.23413301  0.02406648]

You can also use ast.literal_eval :

import ast
import re

ast.literal_eval(re.sub(r'\s+', ',', s))
# [-0.0597212, 0.00344087, -0.23413301, 0.02406648]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM