Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Better way to remove multiple words from a string?

bannedWord = ["Good", "Bad", "Ugly"]
    
def RemoveBannedWords(toPrint, database):
    statement = toPrint
    for x in range(0, len(database)):
        if bannedWord[x] in statement:
            statement = statement.replace(bannedWord[x] + " ", "")
    return statement
        
toPrint = "Hello Ugly Guy, Good To See You."
    
print(RemoveBannedWords(toPrint, bannedWord))

The output is Hello Guy, To See You. Knowing Python I feel like there is a better way to implement changing several words in a string. I searched up some similar solutions using dictionaries but it didn't seem to fit this situation.

like image 299
Andy Wong Avatar asked Jul 07 '15 15:07

Andy Wong


People also ask

How do I remove multiple words from a string in Java?

String url = "http://www.superfect.com"; String[] purge = {"http://", "www."}; url = url. replace(purge, "");

How do you remove multiple words from a sentence in Python?

To strip multiple characters in Python, use the string strip() method. The string strip() method removes the whitespace from the beginning (leading) and end (trailing) of the string by default. The strip() method also takes an argument, and if you pass that argument as a character, it will remove it.


2 Answers

I use

bannedWord = ['Good','Bad','Ugly']
toPrint = 'Hello Ugly Guy, Good To See You.'
print(' '.join(i for i in toPrint.split() if i not in bannedWord))
like image 166
Shreevardhan Avatar answered Sep 19 '22 18:09

Shreevardhan


Here's a solution with regex:

import re
    
def RemoveBannedWords(toPrint,database):
    statement = toPrint
    pattern = re.compile("\\b(Good|Bad|Ugly)\\W", re.I)
    return pattern.sub("", toPrint)
    
toPrint = "Hello Ugly Guy, Good To See You."
    
print(RemoveBannedWords(toPrint,bannedWord))
like image 28
Ajay Gupta Avatar answered Sep 17 '22 18:09

Ajay Gupta