Remove text between () and [] in python

前端 未结 4 1653
我寻月下人不归
我寻月下人不归 2020-11-28 08:44

I have a very long string of text with () and [] in it. I\'m trying to remove the characters between the parentheses and brackets but I cannot figu

4条回答
  •  时光取名叫无心
    2020-11-28 09:04

    Here's a solution similar to @pradyunsg's answer (it works with arbitrary nested brackets):

    def remove_text_inside_brackets(text, brackets="()[]"):
        count = [0] * (len(brackets) // 2) # count open/close brackets
        saved_chars = []
        for character in text:
            for i, b in enumerate(brackets):
                if character == b: # found bracket
                    kind, is_close = divmod(i, 2)
                    count[kind] += (-1)**is_close # `+1`: open, `-1`: close
                    if count[kind] < 0: # unbalanced bracket
                        count[kind] = 0  # keep it
                    else:  # found bracket to remove
                        break
            else: # character is not a [balanced] bracket
                if not any(count): # outside brackets
                    saved_chars.append(character)
        return ''.join(saved_chars)
    
    print(repr(remove_text_inside_brackets(
        "This is a sentence. (once a day) [twice a day]")))
    # -> 'This is a sentence.  '
    

提交回复
热议问题