python – How to strip a specific word from a string?

python – How to strip a specific word from a string?

Use str.replace.

>>> papa.replace(papa, )
 is a good man
>>> app.replace(papa, )
app is important

Alternatively use 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

Easiest way would be to simply replace it with an empty string.

s = s.replace(papa, )

python – How to strip a specific word from a string?

You can also use a regexp with 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)

Leave a Reply

Your email address will not be published. Required fields are marked *