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

I can´t seem to find why my code does not consider the first word "hey"

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

print censor("hey hey hey", "hey")


A lot of moving parts in this code. Do we really need all that? It can be tricky working with the remove method if we are not quite sure what we've got our hands on, that's one possible area for concern.

On a critical note, one does not want to declare a constant inside a loop. If it's constant, then it rightly belongs outside, and before the loop. (oops)

Any lines after return are unreachable, so this line won't be seen,

See if you cannot conceive of an algorithm that does not use .remove().

On a technical note,

In truth, newtext is not a new list, but a reference to the text list. Any changes in this list are made directly to text.


is an in-place method, meaning it acts directly upon the context object, text. Since reference objects such as lists are not assignable, newtext is just a pointer to that object.

To create a separate list, assign it as a sorted copy...

newtext = sorted(text)


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