我正在做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