python - 替换字符串中的文本会产生 TypeError: 'in' 需要字符串作为左操作数,而不是列表
问题描述
我试图通过替换它们来审查一些单词,但它给出了错误:TypeError: 'in <string>' requires string as left operand, not list
.
def censor(text, blacklist):
if blacklist in text:
text= text.replace(blacklist, "*" * len(blacklist))
return text
censor("this is annoying me", ["annoying"])
解决方案
如果您仔细阅读错误,您会看到 Python 抱怨您正在尝试检查 alist
是否在 astring
中。你写了blacklist in text
,但因为blacklist
是一个列表,你不能这样做。
相反,您应该遍历黑名单中的单词并检查每个单词,如下所示:
def censor(text, blacklist):
for word in blacklist:
if word in text:
text = text.replace(word, "*" * len(word))
return text
推荐阅读
- react-native - react native ble plx:写入失败后断开连接
- bash - FFMPEG 编码上的 Plex DVR 文件重命名
- r - 提高 R(terra 包和 vrt)中 150gb+ 栅格图块的区域统计计算速度
- mysql - MySql 在 if() 条件下使用 replace()
- haskell - 在运行时通过servant更改web-root(或路径前缀)?
- scala - 如何在scala的map操作中更新每个str2 ListBuffer[(str1:String,Str2:String),(str1:String,Str2:String)]
- c# - 选择 SQL Server C# 和数组并返回
- javascript - , ,的 HTMLElement 类型
, 和别的 - big-o - 堆的最坏情况 Big-O 运行时
- vue.js - Uncaught (in promise) TypeError: Cannot read property 'catch' of undefined