首页 > 解决方案 > Python字符串操作,通过找到右括号到左括号来删除内容

问题描述

问题是从左括号'['到右括号']'中删除内容
我设法把它写出来,但由于输出不是问题想要的,我没有通过给我的某些测试用例。

我得到的一个提示是,首先找到首要的右括号']',然后追溯到最新的左括号'[',并删除从首要右括号到最新的左括号的所有内容。
但是,我不知道如何写出来。感谢您的帮助

我的代码如下:

def trial():
    b = False
    user_input = input("test cases : ")
    formatstr = ""
    for i in user_input:
        if '[' in i:
            b = True
        elif not b:
            formatstr += i
        if ']' in i:
            b = False
     print(formatstr)
 trial()

这些是具有所需输出的测试用例。

接下来是我的输出,它失败了一些测试用例

[[bean]abc  → [abc  
**My Output = abc**  `Testcase failed`    
    
 [bean]]abc → ]abc  
**My Ouput = ]abc** `Testcase passed`
    
 abc[foo][qwerty] → abc  
**My Output = abc** `Testcase passed`
    
 abc[qwerty]bean] → abcbean]  
**My Output = abcbean]** `Testcase passed`
 
  abc[qwerty[bean] → abc[qwerty
**My Output = abc**  `Testcase failed`
   
  bean[abc[qwe]dfg] → bean
**My Output = beandfg]**  `Testcase failed`

标签: pythonstring

解决方案


您通常通过实现堆栈来处理嵌套结构。当您遇到 a 时,"["您将一个项目添加到堆栈中,并且当您从堆栈中遇到 a"]"pop()。否则,您将追加添加到堆栈顶部的项目。在您的示例中,您需要确保添加实际的括号,因为测试似乎需要它们。这可能看起来像:

def trial(user_input):
    groups = ['']
    for i in user_input:
        if i == '[':
            groups.append(i)
        elif i == ']' and len(groups) > 1:          
            groups.pop()
        else:
            groups[-1] += i
    return "".join(groups)

assert(trial("[[bean]abc") == "[abc")
assert(trial("[bean]]abc") == "]abc")
assert(trial("abc[foo][qwerty]") == "abc")
assert(trial("abc[qwerty]bean]") == "abcbean]")
assert(trial("abc[qwerty[bean]") == "abc[qwerty")
assert(trial("bean[abc[qwe]dfg]") == "bean")

# all pass

推荐阅读