Could any one help me with Censor question?


As shown below, the console prompted that

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

However I cannot get the point why it is the case like that. Could anyone help me out of it?

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


Here's how I did it:

def censor(text, word):
    new = []
    for i in text.split(): #iterates over every word in the string
        if i == word: # If one of the words = to the word you want censored
            i = '*' * len(word) #if it is multiply '*' with the each letter (you got this)
            new.append(i) #then you wanna add it to the empty list
        elif i != word: #Now, if one words doesn't qualify as a censored one
            new.append(i) #Simply, add it to the empty string.
    return ' '.join(new) #adds them up to the final list.
print censor('Holy shit', 'shit')

Hope this helps out with your confusion :slight_smile:


The join statement on line 7 has a space which is why it produces * * * instead of ***
try: text_2 = "".join(item)
instead of: text_2 = " "join(item)

Also the reason it is only replacing one of the "hey"s is because you are returning text_2 on line 8 but in line 7 you told the function that text_2 only equals: " ".join(item) before this on line 6 you told the function that: item = "*" * len(word)

so if "item" is equal to * times the length of the word, then you will only get *s for however long the word is, but it doesn't compensate for how many times the word is in the text because you are only returning the "replacement" for the word itself.

In summary all you really need to do to finish this is to find a way to insert text_2 into every spot where "word" appears. The for loop doesn't actually do the replace for each one, right now its just using each word as the number of times it will repeat the process of assigning text_2 to "***"

sorry if thats a poor explanation, let me know if i can clarify further.


So i was working with your code, trying to modify it to find a way to make it work and accidentally made a dirty rap song about fruit.


This should work:

def censor(text, word):
    text = text.split()
    text_2 = ""
    for item in text:
        if item == word:
            item = "*" * len(word)
        text_2 = text_2 + " " + item
    return text_2

print(censor("This is a text.","is"))

You have to indent your assignment to text_2 into the for-loop. Otherwise it will only execute once (the last item).


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