我正在做Codecademy上的Python,试图检查文本中的单词。代码的作品,但如果文本中的最后一个词有这个词,它不会被审查。Python:在文本中检查一个单词,但最后一个单词不检查
我认为for
声明需要改变,如for x in (text + 1)
,但当然这会导致错误。我们不使用内置函数,如replace()
有什么想法?
def censor(text,word):
text = text.split()
for x in text:
if x == word:
text[text.index(x)] = "*" * len(word)
return " ".join(text)
print(censor("You dirty guy and dirty boy dirty.", "dirty"))
这将返回[You ***** guy and ***** boy dirty.]
我建议你使用'海峡更换工作。替换'或're.sub' – Dmitry
我同意你不能使用替换,但你可以使用拆分,索引,len,加入和打印。所有内置插件 – crowie
你可以改变你的测试去除标点符号:'if x.translate(None,string.punctuation)== word:' – samgak