Deltos Deltos - 2 months ago 7
Python Question

Script which replaces specific words in text by asterisks (Python)

I tried to create a function which finds a censored word (which is an argument of the function) in a text (which is a second argument) and replaces all the instances of the word with astrerisks.

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)


But when I call the function inside the function itself it stops working.

And returns "None". Why? How can I make it work?

And what are the rules of callling a function within the same function?

Answer

You need to return the recursive result like this:

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)

This happens because the function ends in the if statement, resulting None.

Comments