【问题标题】:I need to remove everything inside the parentheses without import re我需要删除括号内的所有内容而不使用 import re
【发布时间】: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


【解决方案1】:

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

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:(取决于您的需要)。

【讨论】:

    猜你喜欢
    • 2022-11-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-24
    • 1970-01-01
    • 1970-01-01
    • 2011-10-18
    相关资源
    最近更新 更多