1

これは私が直面している問題です。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)
4

3 に答える 3

4

Nonereturn ステートメントがない場合、関数は戻ります。

おそらく再帰を実行している間if word in text:は False になるため、何も返されません。また、再帰ステップを返しませんでした。あなたは帰らなければなりません censor(new_word,word)

于 2013-07-07T01:12:45.320 に答える
2

if終わりに向かっての最初のブランチに戻っていません。それをに変更します

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

関数word in textは false の場合も Noneelseを返すため、末尾に を追加して、空の文字列またはその他のデフォルト値を返すことができます。

于 2013-07-07T01:12:27.210 に答える
0

関数が「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
于 2013-07-07T02:41:06.993 に答える