如何从字符串中删除特定单词?

2024-04-26 03:38:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要从字符串中去掉一个特定的单词。

但我发现python strip方法似乎无法识别有序单词。只需去掉传递给参数的任何字符。

例如:

>>> papa = "papa is a good man"
>>> app = "app is important"
>>> papa.lstrip('papa')
" is a good man"
>>> app.lstrip('papa')
" is important"

我怎样才能用python删除指定的单词?


Tags: 方法字符串app参数is字符单词good
3条回答

最简单的方法是用空字符串替换它。

s = s.replace('papa', '')

您还可以将regexp与re.sub一起使用:

article_title_str = re.sub(r'(\s?-?\|?\s?Times of India|\s?-?\|?\s?the Times of India|\s?-?\|?\s+?Gadgets No'',
                           article_title_str, flags=re.IGNORECASE)

使用str.replace

>>> papa.replace('papa', '')
' is a good man'
>>> app.replace('papa', '')
'app is important'

或者使用^{}和正则表达式。这将允许删除前导/尾随空格。

>>> import re
>>> papa = 'papa is a good man'
>>> app = 'app is important'
>>> papa3 = 'papa is a papa, and papa'
>>>
>>> patt = re.compile('(\s*)papa(\s*)')
>>> patt.sub('\\1mama\\2', papa)
'mama is a good man'
>>> patt.sub('\\1mama\\2', papa3)
'mama is a mama, and mama'
>>> patt.sub('', papa3)
'is a, and'

相关问题 更多 >