10. censor


Task: Write a function called censor that takes two strings, text and word, as input. It should return the text with the word you chose replaced with asterisks.

Error: Your function fails on censor("hey hey hey","hey"). It returns "['hey', 'hey', 'hey']" when it should return "*** *** ***".

def censor(text, word):
    split = text.split(" ")
    return split
    for i in split:
        if i == word:
            i = "*" * len(word)
            return i
    return " ".join(split)

Any suggestions are greatly appreciated!


Remove this line.

We cannot reassign a value to the iterator, plus you do not want to return before completing the loop.

result = []
for i in split:     # not sure this is the best choice of variable name.
    if i == word:
        resuilt.append("*" * len(word))
return " ".join(result)


Thank you @mtf, you never disappoint. I will keep these things in mind!

Just curious, why is "i in split" a poor choice of variable name(s)?


Because split is a reserved word and using it as a variable, while there may not be a conflict, makes reading and debugging a lttle trickier. Best to invent variable names that are purpose and role based in meaning.