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

但我发现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剥离指定的单词?

最佳答案

使用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'

关于python - 如何从字符串中剥离特定单词?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/23669024/

10-10 09:38