0
該函數應返回文本與字替換爲星號。 不知道爲什麼我的原始代碼不會工作,因爲邏輯似乎對我來說是正確的。替換python中的列表元素
text = "this shit is cool"
def censor(text, word):
lst = text.split()
ast = ""
result = ''
for char in word:
ast += "*"
for wrd in lst:
if wrd == word:
wrd = ast #why doesn't this part work??
print " ".join(lst)
censor(text, "shit")
這是我查找了一些其他相關問題後更正的代碼。它似乎更復雜和不必要。爲什麼這個工作而不是我的原始代碼?
def censor(text, word):
lst = text.split()
ast = ""
result = ''
for char in word:
ast += "*"
for wrd in lst:
if wrd == word:
loc = lst.index(word) #I can't just change it directly? using wrd?
lst[loc] = ast
return " ".join(lst)