我有一个用户输入的字符串,我想搜索它并用我的替换字符串替换所有出现的单词列表。
import re
prohibitedWords = ["MVGame","Kappa","DatSheffy","DansGame","BrainSlug","SwiftRage","Kreygasm","ArsonNoSexy","GingerPower","Poooound","TooSpicy"]
# word[1] contains the user entered message
themessage = str(word[1])
# would like to implement a foreach loop here but not sure how to do it in python
for themessage in prohibitedwords:
themessage = re.sub(prohibitedWords, "(I'm an idiot)", themessage)
print themessage
上面的代码不起作用,我确定我不明白 python for 循环是如何工作的。
原文由 Zac 发布,翻译遵循 CC BY-SA 4.0 许可协议
您可以通过一次调用
sub
来做到这一点:例子:
请注意,使用
str.replace
可能会导致细微的错误:使用
re.sub
给出正确的结果:正如 thg435 指出的那样,如果你想替换 单词 而不是每个子字符串,你可以将单词边界添加到正则表达式中:
这将替换
'random'
中的'random words'
但不是'pseudorandom words'
中的。