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.
>>> papa = "papa is a good man" >>> app = "app is important" >>> papa.lstrip('papa') " is a good man" >>> app.lstrip('papa') " is important"
How could I strip a specified word with python?
This question is tagged with
~ Asked on 2014-05-15 03:59:01
>>> papa.replace('papa', '') ' is a good man' >>> app.replace('papa', '') 'app is important'
re and use regular expressions. This will allow the removal of leading/trailing spaces.
>>> 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'
~ Answered on 2014-05-15 04:02:05
Easiest way would be to simply replace it with an empty string.
s = s.replace('papa', '')
~ Answered on 2014-05-15 04:02:03