该函数应返回文本,并将字替换为星号。 不知道为什么我的原始代码不会起作用,因为逻辑对我来说是正确的。
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)
答案 0 :(得分:0)
试试这个:
def censor(text,word):
return text.replace(word,'*'*(len(word)))