I need to strip a specific word from a string.
But I find python strip method seems can’t recognize an ordered word. The just strip off any characters passed to the parameter.
For example:
JavaScript
x
7
1
>>> papa = "papa is a good man"
2
>>> app = "app is important"
3
>>> papa.lstrip('papa')
4
" is a good man"
5
>>> app.lstrip('papa')
6
" is important"
7
How could I strip a specified word with python?
Advertisement
Answer
Use str.replace
.
JavaScript
1
5
1
>>> papa.replace('papa', '')
2
' is a good man'
3
>>> app.replace('papa', '')
4
'app is important'
5
Alternatively use re
and use regular expressions. This will allow the removal of leading/trailing spaces.
JavaScript
1
13
13
1
>>> import re
2
>>> papa = 'papa is a good man'
3
>>> app = 'app is important'
4
>>> papa3 = 'papa is a papa, and papa'
5
>>>
6
>>> patt = re.compile('(s*)papa(s*)')
7
>>> patt.sub('\1mama\2', papa)
8
'mama is a good man'
9
>>> patt.sub('\1mama\2', papa3)
10
'mama is a mama, and mama'
11
>>> patt.sub('', papa3)
12
'is a, and'
13