我需要从字符串中删除特定的单词.
但我发现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'