如何从字符串中去除特定单词?
我需要从一个字符串中去掉一个特定的单词。
但是我发现 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 去掉一个指定的单词呢?
9 个回答
4
你也可以用正则表达式配合 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)
8
如果你想要只从字符串的开头去掉某个词,可以这样做:
string[string.startswith(prefix) and len(prefix):]
这里的string是你要处理的字符串变量,而prefix是你想从这个字符串变量中去掉的前缀。
举个例子:
>>> papa = "papa is a good man. papa is the best."
>>> prefix = 'papa'
>>> papa[papa.startswith(prefix) and len(prefix):]
' is a good man. papa is the best.'
17
如果我们在讨论前缀和后缀,而且你的Python版本至少是3.9,那你可以使用这些新方法:
>>> 'TestHook'.removeprefix('Test')
'Hook'
>>> 'BaseTestCase'.removeprefix('Test')
'BaseTestCase'
>>> 'MiscTests'.removesuffix('Tests')
'Misc'
>>> 'TmpDirMixin'.removesuffix('Tests')
'TmpDirMixin'
20
最简单的方法就是把它替换成一个空字符串。
s = s.replace('papa', '')
127
可以使用 str.replace
方法。
>>> papa.replace('papa', '')
' is a good man'
>>> app.replace('papa', '')
'app is important'
另外,你也可以使用 re
模块,利用正则表达式。这种方法可以帮助你去掉字符串开头和结尾的空格。
>>> 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'