Censor - returns empty spaces


Can't figure it how I ended up with empty spaces separated by commas in a list. Any thoughts?
I know that I still have to re-joint the string, but makes no sense if I get only joint empty spaces...
The more I adjust on the code, the worst it gets really...

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

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

Replace this line with your code.


Why are you calling to word in your variable text?

text = text.split(word)

You should remove word from between the parentheses. As secondary, look again at your for loop. You are using a parameter to loop over things, where you need that just defined variable. Believe me, this confuses the code a LOT, so remove them and maybe call them as X:s, Y:s or ITEM;s?


Thanks! You're right. The for loop just got confused. I inserted some more items, and appended to an empty list.
Looking backwards, it looks now so simple...

def censor(text, word):
    words = text.split(" ")
    newtext = []
    for letter in words:
        if letter == word:
            newtext.append("*" * len(word))
        else: newtext.append(letter)
    return " ".join(newtext)


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