Python 字符串拆分多个括号
Python string split multiple brackets
我正在寻找一种更简单/更快的方法来通过方括号/圆括号拆分字符串,以及删除空格和无用信息。
更具体地说,我想改变
[ 5 * * ]{t=0, 1 }{t=0, 3 }{t=0, 2 }
分两部分:
5 * * (or [ 5 * * ])
['1', '3', '2']
我设法使用我的代码做到了这一点:
test = '[ 5 * * ]{t=0, 1 }{t=0, 3 }{t=0, 2 } '
parsed = test.split("[")[1].split(']')
index = parsed[0]
content = parsed[1].split('{')[1:]
seq=[]
for i in range(len(content)):
seq.append(content[i][4:-2].replace(' ', ''))
print index
print seq
得到:
5 * *
['1', '3', '2}']
我正在寻找修改代码的建议。这将是理想的:
会没有循环。
少'split'。 (我的代码里有3个'split'函数)
更一般。 (我使用 content[i][4:-2] 删除了不通用的 '{' 和 '}' )
您可以使用 re.findall
和列表理解:
>>> l=re.findall(r'\[([^\]]*)\]|,([^}]*)}',s)
>>> [i.strip() for j in l for i in j if i]
['5 * *', '1', '3', '2']
以下正则表达式:
r'\[([^\]]*)\]|,([^}]*)}'
将匹配方括号 (\[([^\]]*)\]
) 和逗号与 }
之间的所有内容 (,([^}]*)}
).
或者您可以使用 re.split()
:
>>> [i.strip() for i in re.split(r'[{},[\]]',s) if i and '=' not in i]
['5 * *', '1', '3', '2']
我正在寻找一种更简单/更快的方法来通过方括号/圆括号拆分字符串,以及删除空格和无用信息。
更具体地说,我想改变
[ 5 * * ]{t=0, 1 }{t=0, 3 }{t=0, 2 }
分两部分:
5 * * (or [ 5 * * ])
['1', '3', '2']
我设法使用我的代码做到了这一点:
test = '[ 5 * * ]{t=0, 1 }{t=0, 3 }{t=0, 2 } '
parsed = test.split("[")[1].split(']')
index = parsed[0]
content = parsed[1].split('{')[1:]
seq=[]
for i in range(len(content)):
seq.append(content[i][4:-2].replace(' ', ''))
print index
print seq
得到:
5 * *
['1', '3', '2}']
我正在寻找修改代码的建议。这将是理想的:
会没有循环。
少'split'。 (我的代码里有3个'split'函数)
更一般。 (我使用 content[i][4:-2] 删除了不通用的 '{' 和 '}' )
您可以使用 re.findall
和列表理解:
>>> l=re.findall(r'\[([^\]]*)\]|,([^}]*)}',s)
>>> [i.strip() for j in l for i in j if i]
['5 * *', '1', '3', '2']
以下正则表达式:
r'\[([^\]]*)\]|,([^}]*)}'
将匹配方括号 (\[([^\]]*)\]
) 和逗号与 }
之间的所有内容 (,([^}]*)}
).
或者您可以使用 re.split()
:
>>> [i.strip() for i in re.split(r'[{},[\]]',s) if i and '=' not in i]
['5 * *', '1', '3', '2']