如何修复此"Generator expression must be parenthesized if not sole argument"错误?



我正在编写一个程序来审查一些单词。

def censor(sentence, word):
splitted_sentence = sentence.split()  #splitted_sent = ["he", "is", "a", "clucking", "boy"]
censored = [item.replace(item, "*" * len(item) for item in word)]
return censored
print censor("he is a clucking boy", "clucking")  

在这个例子中,我想做的是过滤句子中的"咯咯"这个词。但是当我运行它时,它说:

生成器表达式必须括起来,如果不是唯一的参数。

不需要列表理解来使简单的事情复杂化。请在下面找到用于执行相同操作的简单代码。

def fun(sen,word):
sen=sen.replace(word, len(word)*"*")
return sen
print(fun("he is a clucking boy","clucking")) #he is a ******** boy

可能你放错了括号。试试这个:

censored = [item.replace(item, "*" * len(item)) for item in word]

相关内容

最新更新