2016-09-24 61 views
0

我試圖創建一個函數,該函數在文本(它是第二個參數)中查找刪減的單詞(該函數是一個參數)並替換所有實例與astrerisks一詞。通過星號替換文本中特定單詞的腳本(Python)

def censor(text, word): 
    if word in text: 
     position = text.index(word) 
     new_text = text[0: position] + "*"*len(word) + text[position+len(word):] 
     censor(new_text,word) 
    else: 
     return text 


phrase_with = raw_input("Type the sentence") 
foo= raw_input("Type the censored word") 
print censor(phrase_with, foo) 

但是當我調用函數內部的函數時,它停止工作。

並返回「」。爲什麼?我怎樣才能使它工作?

在同一個函數中調用函數的規則是什麼?

+0

不是最有效的代碼。 'def censor(text,word):return(「*」* 4).join(text.split(word))'會做。 –

+0

是啊!我明白。但鑑於我在學習Python的第三天,我對自己感到非常滿意。到目前爲止,你對我看起來很神祕。但是謝謝你! –

+0

這不是遠程工作的遞歸。同時儘量避免你的問題中的褻瀆。 –

回答

0

您需要返回遞歸的結果是這樣的:

def censor(text, word): 
    if word in text: 
     position = text.index(word) 
     new_text = text[0: position] + "*"*len(word) + text[position+len(word):] 
     return censor(new_text,word) # <-- Add return here 
    else: 
     return text 


phrase_with_fuck = raw_input("Type the sentence") 
fuck = raw_input("Type the censored word") 
print censor(phrase_with_fuck, fuck) 

這是因爲功能在if語句結束,從而導致無。

+0

非常感謝,佐丹奴! –