在python中查找并删除以特定子字符串开头和结尾的字符串 [英] Find and remove a string starting and ending with a specific substring in python

查看:164
本文介绍了在python中查找并删除以特定子字符串开头和结尾的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类似于 "dasdasdsafs[image : image name : image]vvfd gvdfvg dfvgd" 的字符串.从这个字符串中,我想删除从 [image : 开始并以 : image] 结尾的部分.我尝试使用以下代码找到子字符串"-

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

但它没有给我所需的结果.帮我找到从字符串中删除子字符串的正确方法.

解决方案

您可以使用 re.sub :

<预><代码>>>>s='dasdasdsafs[图像:图像名称:图像]vvfd gvdfvg dfvgd'>>>re.sub(r'\[image.+image\]','',s)'dasdasdsafsvvfd gvdfvg dfvgd'

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.

解决方案

You can use re.sub :

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

这篇关于在python中查找并删除以特定子字符串开头和结尾的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆