我正在尝试拆分包含 python 函数的字符串,以便生成的输出将单独的函数保留为列表元素。
s='hello()there()'应该拆分为['hello()', 'there()']
为此,我使用正则表达式先行在右括号上拆分,但不在字符串末尾拆分。
虽然前瞻似乎有效,但我无法)按照各种帖子中的建议将结果保留在结果字符串中。简单地用正则表达式分割会丢弃分隔符:
import re
s='hello()there()'
t=re.split("\)(?!$)", s)
Run Code Online (Sandbox Code Playgroud)
这导致:'hello(', 'there()']。
s='hello()there()'
t=re.split("(\))(?!$)", s)
Run Code Online (Sandbox Code Playgroud)
将分隔符包装为一个组会导致)保留为一个单独的元素:与使用该函数的方法['hello(', ')', 'there()']
一样:filter()
s='hello()there()'
u = list(filter(None, re.split("(\))(?!$)", s)))
Run Code Online (Sandbox Code Playgroud)
再次导致括号作为单独的元素:['hello(', ')', 'there()']
如何拆分这样的字符串以使函数在输出中保持完整?