【发布时间】:2021-07-11 05:01:50
【问题描述】:
我有一个字符串:
my_string = "[some tag1][tag 2] Some text"
如何在 Python 3 中从字符串中删除标签?
【问题讨论】:
-
你试过什么?
re模块和re.sub可以解决这个问题。
标签: python python-3.x string parsing
我有一个字符串:
my_string = "[some tag1][tag 2] Some text"
如何在 Python 3 中从字符串中删除标签?
【问题讨论】:
re 模块和 re.sub 可以解决这个问题。
标签: python python-3.x string parsing
您可以使用正则表达式:
import re
my_string = " [The Tag before the text works] The text [The Tag after the text does not work]"
result = re.sub(r'\s*\[.+?\]\s*', '', my_string)
lstrip() 将去除标签和文本之间的空白。
【讨论】:
] 并且仅由于回溯。考虑创建一个否定字符类或使用不情愿的量词。