如何删除括号内的内容而不删除括号

string="file()(function)(hii)out(return)(byee)"

对于这个字符串,我需要像这样的输出

file()()()out()()
file()()()out()()

我试过这个

string="file()(function)(hii)out(return)(byee)"
string1=re.sub("[([].*?[)]]", "", string)
string2=re.sub(r" ?([^)]+)", "", string)

print(string1)
print(string2)

并得到类似的输出

fileout

file()out

我想要的输出应该是这样的:

回答

使用正则表达式:捕获括号之间的所有内容,即(.*?)并将其替换为空字符串即( )

import re

x = "file()(function)(hii)out(return)(byee)"
x = re.sub("(.*?)", "()", x)
print(x)

这将打印

文件()()()输出()()


以上是如何删除括号内的内容而不删除括号的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>