首页 > 解决方案 > 替换字符串中的文本会产生 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

解决方案


如果您仔细阅读错误,您会看到 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

推荐阅读