Censor returnig "None"


#1



10.censor


It's printing the correct answer but isn't returning it.

Error: Oops, try again. Your function fails on censor("hey hey hey","hey"). It returns "None" when it should return "*** *** ***".

def censor(text,word):
    if text.index(word):
        rplc=text.replace(word,"*"*len(word),100)
        return rplc

censor("this idea is a idea bad idea","idea")


#2

When word is at index 0 this will yield False. Since your return statement is inside the if block, there is no return, hence, None.

Now when the return statement is taken out of the block (moved 4 spaces left) an exception is raised.

Traceback (most recent call last):
  File "<stdin>", line 10, in <module>
  File "<stdin>", line 7, in censor
UnboundLocalError: local variable 'rplc' referenced before assignment

Suggest drop the conditional and just act on the text directly, then return it.

return text.replace(word, "*" * len(word))

I would also suggest trying some other approaches besides the built-in. Something this simple can hardly be called practice.


#3

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.