【发布时间】:2021-02-02 14:25:41
【问题描述】:
我需要删除括号和其中的所有内容
我写了一个代码
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”。
【问题讨论】:
-
while ")" in c表示只要列表中还有 any),您的函数就会继续删除字符。您需要对其进行重构,使其仅pops 直到下一个)。 -
您还需要更改逻辑以便它处理断开的括号,例如“word1(第一组)word2(第二组)word3”。很简单,你还没有考虑完整的问题。您必须研究如何匹配括号,然后编写代码来处理您的实际问题。
标签: python string function python-3.8 parentheses