我试着执行这段代码,但是在输出中,最后一个单词-hack没有变成星号,甚至没有显示出来。
在此输入代码:
def censor(text,word):
w=""
text1=""
for i in text:
if i==" ":
if w==word:
text1=text1+"*"*len(word)
else:
text1=text1+w
text1=text1+" "
w=""
else:
w=w+i
return text1
print censor("this hack is wack hack", "hack")发布于 2016-09-15 18:31:11
错误发生在函数的第四行。如果您在示例中的"text“结尾添加了一个额外的空间,那么它将打印您想要的内容。如果不对问题发生的原因进行过多的挖掘,下面的内容就会奏效。
def censor(text,word):
text = text + " "
w=""
text1=""
for i in text:
if i==" ":
if w==word:
text1=text1+"*"*len(word)
else:
text1=text1+w
text1=text1+" "
w=""
else:
w=w+i
return text1
print(censor("this hack is wack hack ", "hack"))https://stackoverflow.com/questions/39517934
复制相似问题