wei zeng wei zeng - 22 days ago 6
Python Question

Python removing substring

I want to remove a list of words/phrases in a sentence.

sentence = 'hello thank you for registration'
words_to_remove=['registration','reg','is','the','in','payment','thank you','see all tags']

sentence = ' '.join([word for word in sentence.split() if word not in words_to_remove])


But this does not remove 'thank you' or 'see all tags'

Thanks

Answer

Iterate over the list of words and replace each word using str.replace():

sentence = 'hello thank you for registration'
words_to_remove=['registration','reg','is','the','in','payment','thank you','see all tags']

for word in words_to_remove:
    sentence = sentence.replace(word, '')

At the end, senctence will hold the value:

>>> sentence
'hello  for '
Comments