Find and remove a string starting and ending with a specific substring in python

I have a string similar to "dasdasdsafs[image : image name : image]vvfd gvdfvg dfvgd" . From this string, I want to remove the part which stars from [image : and ends at : image] . I tried to find the 'sub-string' using following code-

result = re.search('%s(.*)%s' % (start, end), st).group(1)

but it doesn't give me the required result. Help me to find the correct way to remove the sub-string from the string.


你可以使用re.sub

>>> s='dasdasdsafs[image : image name : image]vvfd gvdfvg dfvgd'
>>> re.sub(r'[image.+image]','',s)
'dasdasdsafsvvfd gvdfvg dfvgd'

您可能只需要将方括号转义出来,因为这些是正则表达式中的特殊字符(即start = r“ [image:”和end = r“:image ]”)。


这将删除字符串中的所有事件

import re

s = "dasdasdsafs[image : image name : image]vvfd gvdfvg dfvgd"
s = re.sub(r'[image :.*?: image]', r'', s)
链接地址: http://www.djcxy.com/p/55124.html

上一篇: Python:从字符串打印特定字符

下一篇: 查找并移除一个以python中的特定子字符串开始和结束的字符串