Reputation: 43
I need to remove parentheses and everything inside them
I wrote a code
def remove_parentheses(s):
c = list(s)
s1 = c.index('(')
while ")" in c:
c.pop(s1)
c = "".join(c)
c.strip(' ')
return c
but it failed the last test
test.assert_equals(remove_parentheses("(first group) (second group) (third group)"), " ")
with an error
'' should equal ' '
How can i fix this? I can't use "import re" in my case.
Upvotes: 0
Views: 86
Reputation: 13222
I would construct a new list from the string and keep track of the current number of opening and closing brackets while iterating the string.
def remove_parentheses(text):
data = []
counter = 0
for c in text:
if c == '(':
counter += 1
if counter == 0:
data.append(c)
if c == ')':
counter -= 1
return ''.join(data)
If we find a '('
we increase the counter. If we find a ')'
we decrease the counter. Characters are only added to the list if the counter is 0
.
The code needs some additional checks if you can have strings like 'a(b))c)(d(e(f)g'
. In that case the comparison might be if counter <= 0:
(depending on your needs).
Upvotes: 3