将字符串分割成可用的列表(Python)

问题描述 投票:0回答:1

我希望能够将用户输入字符串转换为字符串列表,然后根据需要修改该列表。例如,我将使用:(a+b)(b+a)。最终结果是 list[0]=a+b 和 list[1]=b+a。

到目前为止,我已经弄清楚如何使用 re.split 工具将示例字符串分解为字符串列表。

list[0]=
list[1]=a+b
list[2]=b+a
list[3]=

我想从我的列表中删除空白字符串。

目前我尝试使用过滤器(无,...):如下所示

import re
original = "(a+b)(b+a)"

sections = list()
sections=filter(None,re.split(r"[()]+",original))
print(sections[0])

这给了我:“

TypeError: 'filter' object is not subscriptable
”虽然我理解这个词,但我不完全确定这意味着什么。 我试着把过滤器拉出来:

import re
original = "(a+b)(b+a)"

sections = list()
sections=re.split(r"[()]+",original)
print(sections)
sections=filter(None, sections)
print(sections)

现在我得到了“”,这对我来说比上面的话更没有意义。请帮我删除空白字符串。预先感谢。

python-3.x string list filter split
1个回答
0
投票

实际上,

re.findall
与正则表达式模式
\((.*?)\)
是一个更好的工具:

import re
original = "(a+b)(b+a)"

parts = re.findall(r'\((.*?)\)', original)
print(parts)  # ['a+b', 'b+a']
© www.soinside.com 2019 - 2024. All rights reserved.