how to remove content inside bracket without removing brackets

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

for this string i need output like

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

I have tried this

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

print(string1)
print(string2)

and got output like

fileout

file()out

my desired output should look like this:

file()()()out()()
1 Answers

use regex: capture all between Parentheses, i.e. (.*?) and replace it with an empty string i.e. ( )

import re

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

this will print

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

Related