我希望能够将用户输入字符串转换为字符串列表,然后根据需要修改该列表。例如,我将使用:(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)
现在我得到了“
实际上,
re.findall
与正则表达式模式\((.*?)\)
是一个更好的工具:
import re
original = "(a+b)(b+a)"
parts = re.findall(r'\((.*?)\)', original)
print(parts) # ['a+b', 'b+a']