如果生成器不能用圆括号括起来,怎么能修正这个表达式?

2024-10-01 09:20:14 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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”。但当我运行它时,它说:

Generator expression must be parenthesized if not sole argument.


Tags: 程序isdefitem单词sentencewordsent
2条回答

不需要列表理解来使简单的事情复杂化东西。拜托找到下面的简单代码做同样的事情。在

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]

相关问题 更多 >