问题描述
我需要删除括号及其中的所有内容
我写了一个代码
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:
(取决于您的需求)。