我需要删除括号和其中的所有内容
我写了一段代码
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)
如果我们找到 a'('
我们增加计数器。如果我们找到 a')'
我们减少计数器。如果计数器为 ,则字符仅添加到列表中0
。
代码需要一些额外的检查,如果你可以有像'a(b))c)(d(e(f)g'
. 在这种情况下,比较可能是if counter <= 0:
(取决于您的需要)。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句