Remove text between () and [] in python

前端 未结 4 1655
我寻月下人不归
我寻月下人不归 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:09

    You can use re.sub function.

    >>> import re 
    >>> x = "This is a sentence. (once a day) [twice a day]"
    >>> re.sub("([\(\[]).*?([\)\]])", "\g<1>\g<2>", x)
    'This is a sentence. () []'
    

    If you want to remove the [] and the () you can use this code:

    >>> import re 
    >>> x = "This is a sentence. (once a day) [twice a day]"
    >>> re.sub("[\(\[].*?[\)\]]", "", x)
    'This is a sentence.  '
    

    Important: This code will not work with nested symbols

提交回复
热议问题