【发布时间】:2014-03-03 05:34:11
【问题描述】:
通过 codeacademy for python,一项任务是编写一个函数,该函数将接受一个字符串并用星号删去某个单词,然后返回该字符串。我尝试了一种方法,但它没有用,但我又尝试了另一种方法,它成功了。我只是好奇为什么。
那个没用的:
def censor(text, word):
split_string = text.split()
replace_string = "*" * len(word)
for i in split_string:
if i == word:
i = replace_string
return " ".join(split_string)
确实有效的那个:
def censor(text, word):
split_string = text.split()
replace_string = "*" * len(word)
for i in range(0, len(split_string)):
if split_string[i] == word:
split_string[i] = replace_string
return " ".join(split_string)
【问题讨论】:
标签: python python-2.7