Python 如何修复“如果不是唯一参数,则生成器表达式必须用括号括起来”错误?
我正在写一个程序来审查一些单词Python 如何修复“如果不是唯一参数,则生成器表达式必须用括号括起来”错误?,python,python-2.7,Python,Python 2.7,我正在写一个程序来审查一些单词 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 cluc
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")
在这个例子中,我想做的是过滤句子中的单词clucking。但当我运行它时,它会说:
如果不是唯一参数,则生成器表达式必须加括号
可能你放错了括号。试试这个:
censored = [item.replace(item, "*" * len(item)) for item in word]
不需要列表理解就可以使简单的事情复杂化。请找到下面做同样事情的简单代码
def fun(sen,word):
sen=sen.replace(word, len(word)*"*")
return sen
print(fun("he is a clucking boy","clucking")) #he is a ******** boy
你能不能选择一个更“儿童友好”的词作为例子?对于所有年龄和背景的人也是如此,请返回句子。替换项,**lenitem。split@Chris_Rands首先,谢谢你的回答,下次我一定会选择一个更合适的词。接下来,当我按照您的建议修改代码后尝试运行代码时,它会打印:['he','is','a','clucking','boy'],而不是['he','is','a','xxxxxxxx','boy'],这是一个偏执,这是一个大括号},无论如何,它会标记并且不会回答打字错误