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)
输出为
Hello Guy, To See You.
。了解Python我感觉有一种更好的方法来实现更改字符串中的多个单词。我使用字典搜索了一些类似的解决方案,但似乎不适合这种情况。 最佳答案
这是正则表达式的解决方案:
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)