我需要删除括号内的所有内容而无需重新导入

I need to remove everything inside the parentheses without import re

我需要删除括号和其中的所有内容

我写了一个代码

def remove_parentheses(s):
    c = list(s)
    s1 = c.index('(')
    while ")" in c:
        c.pop(s1)
    c = "".join(c)
    c.strip(' ')
    return c

但上次测试失败

        test.assert_equals(remove_parentheses("(first group) (second group) (third group)"), "  ")

出现错误

'' should equal '  '

我该如何解决这个问题?我不能在我的案例中使用“import re”。

我会根据字符串构建一个新列表,并在迭代字符串时跟踪当前的左括号和右括号数量。

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)

如果我们找到 '(',我们会增加计数器。如果我们找到 ')',我们会减少计数器。只有当计数器为 0.

时,字符才会添加到列表中

如果您可以使用 'a(b))c)(d(e(f)g' 这样的字符串,则代码需要进行一些额外的检查。在那种情况下,比较可能是 if counter <= 0:(取决于您的需要)。