2016-09-24 9 views
0

テキスト(2番目の引数)に中止された単語(関数の引数)を見つけ出し、すべてのインスタンスを置き換える関数を作成しようとしました驚きの言葉でアスタリスクでテキスト内の特定の単語を置き換えるスクリプト(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を学んだ3日目を迎えていることを踏まえ、私は私のことに満足しています。あなたは今のところ私には不可解に見えます。でもありがとう! –

+0

これは再帰的な作業ではありません。また、あなたの質問から冒涜を守るようにしてください。 –

答えて

0

:機能なし]を結果のない、if文で終わっているため

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) 

これが起こります。

+0

ありがとう、Giordano! –

関連する問題