程序审查错误(codecademy)熟能生巧



我尝试执行这段代码,但在输出中,最后一个word-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")

错误发生在函数的第四行。如果您在示例中的"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"))

最新更新