Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to strip a specific word from a string?

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:

>>> 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?

like image 896
Zen Avatar asked May 15 '14 03:05

Zen


People also ask

How do you strip a word from a string in Python?

Python String strip()The strip() method returns a copy of the string by removing both the leading and the trailing characters (based on the string argument passed).

How do you remove a specific word from text in Python?

Remove a Word from String using replace() print("Enter String: ", end="") text = input() print("Enter a Word to Delete: ", end="") word = input() wordlist = text. split() if word in wordlist: text = text.

How do I find a specific word in a string?

String has a contains() method - you can use that. Is String. indexOf() available in android?


1 Answers

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' 
like image 112
metatoaster Avatar answered Sep 20 '22 08:09

metatoaster