How to strip a specific word from a string?

Question:

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?

Asked By: Zen

||

Answers:

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

s = s.replace('papa', '')
Answered By: iamdev

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'
Answered By: metatoaster

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)
Answered By: Akshay Karapurkar

Providing you know the index value of the beginning and end of each word you wish to replace in the character array, and you only wish to replace that particular chunk of data, you could do it like this.

>>> s = "papa is papa is papa"
>>> s = s[:8]+s[8:13].replace("papa", "mama")+s[13:]
>>> print(s)
papa is mama is papa

Alternatively, if you also wish to retain the original data structure, you could store it in a dictionary.

>>> bin = {}
>>> s = "papa is papa is papa"
>>> bin["0"] = s
>>> s = s[:8]+s[8:13].replace("papa", "mama")+s[13:]
>>> print(bin["0"])
papa is papa is papa
>>> print(s)
papa is mama is papa
Answered By: Michael Strobel

A bit ‘lazy’ way to do this is to use startswith– it is easier to understand this rather regexps. However regexps might work faster, I haven’t measured.

>>> papa = "papa is a good man"
>>> app = "app is important"
>>> strip_word = 'papa'
>>> papa[len(strip_word):] if papa.startswith(strip_word) else papa
' is a good man'
>>> app[len(strip_word):] if app.startswith(strip_word) else app
'app is important'
Answered By: egvo

If want to remove the word from only the start of the string, then you could do:

  string[string.startswith(prefix) and len(prefix):]  

Where string is your string variable and prefix is the prefix you want to remove from your string variable.

For example:

  >>> papa = "papa is a good man. papa is the best."  
  >>> prefix = 'papa'
  >>> papa[papa.startswith(prefix) and len(prefix):]
  ' is a good man. papa is the best.'
Answered By: theQuestionMan

Use replace(): var.replace("word to replace"," replacement word ")

>>> one = "papa is a good man"
>>> two = "app is important"
>>> one.replace("papa ", " ")
" is a good man"
>>> two.replace("app ", " ")
" is important"
Answered By: parth gosai

If we’re talking about prefixes and suffixes and your version of Python is at least 3.9, then you can use these new methods:

>>> 'TestHook'.removeprefix('Test')
'Hook'
>>> 'BaseTestCase'.removeprefix('Test')
'BaseTestCase'

>>> 'MiscTests'.removesuffix('Tests')
'Misc'
>>> 'TmpDirMixin'.removesuffix('Tests')
'TmpDirMixin'
Answered By: qyryq

It is better to

  1. Split the words

  2. Join the ones we are interested in with an if statement (you can pass in multiple words to strip)

    sentence = "papa is a good man"

    ‘ ‘.join(word for word in sentence.split() if word not in [‘papa’])

Answered By: Giri
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.