繁体   English   中英

当我尝试打印该方法返回的字符串时,为什么我的python方法打印出“无”?

[英]Why does my python method print out 'None' when I try to print out the string that the method returns?

这是我遇到的问题,而不是返回new_word并将其打印出来,只是打印“ None”

    text = "hey hey hey,hey"
    word = 'hey'

    def censor(text,word):
        new_word = ""
        count = 0
        if word in text:
            latter_count = ((text.index(word))+len(word))
            while count < text.index(word):
                new_word+= text[count]
                count += 1
            for i in range(len(word)):
                new_word += '*'
            while latter_count < len(text) :
                new_word += text[latter_count]
                latter_count += 1

            if word in new_word :
                censor(new_word,word)
            else :
                return new_word
    print censor(text,word)

如果没有return语句,则函数返回None

可能在执行递归时, if word in text:为False,则没有任何返回值。 您也没有返回递归步骤。 您必须返回 censor(new_word,word)

您不会在if的第一个分支中返回结尾。 更改为

if word in new_word:
    return censor(new_word,word)

如果word in text为false,则函数也将返回None,因此在这种情况下,您可能希望在末尾添加else以返回空字符串或其他一些默认值。

如果函数在没有命中“ return”语句的情况下就结束了,则它与“ return None”相同:

def censor(text,word):
    new_word = ""
    count = 0
    if word in text:
        latter_count = ((text.index(word))+len(word))
        while count < text.index(word):
            new_word+= text[count]
            count += 1
        for i in range(len(word)):
            new_word += '*'
        while latter_count < len(text) :
            new_word += text[latter_count]
            latter_count += 1

        if word in new_word :
            censor(new_word,word)  # probably want to return here
        else :                     # don't need this else if you return in the if branch
            return new_word

    # what do you want to return in this case?
    return None

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM