Skip to content Skip to sidebar Skip to footer

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','

Solution 1:

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

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

forwordin words_to_remove:
    sentence = sentence.replace(word, '')

At the end, senctence will hold the value:

>>> sentence
'hello  for '

Solution 2:

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

Solution 3:

Split 'thank you' in 'thank','you', because that happens when you split 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 notin words_to_remove])>>>sentence
'hello for'
>>>

Post a Comment for "Python Removing Substring"