从字符串中删除多个单词的更好方法? [英] 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)
输出是 Hello Guy, To See You.
了解 Python 我觉得有更好的方法来实现更改字符串中的几个单词.我使用字典搜索了一些类似的解决方案,但似乎不适合这种情况.
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.
推荐答案
这是一个使用正则表达式的解决方案:
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)
这篇关于从字符串中删除多个单词的更好方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文