What is wrong with my censor?


I wrote a "censor" function as follows

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

The exercise should be trivial: I split the input string "text", iterate through it, if I find the forbidden word I replace it with a number of * equal to the word length. I think I'm doing something wrong here:

x=('*' * len(word))

Thank you for your help! :smile:


Those parantheses around '*' * len(word) are unnecessary. Here's my code sample:

def censor(text, word):
    centext = ""
    for w in text.split():
        if w == word:
            centext += "*" * len(w)
            centext += w
        centext += " "
    return centext.strip()


I got the same problem at first.But I thought it over.Just like what i learned in C++,the 'x' in the loop just a copy of text's member.So x=('*' * len(word)) change the copy,not the real item in text.There are 2 method to fix it.The first is to create a new list to store every 'x'.The second is changing the original list.I choose the second way-add some code in your source code:

def censor(text,word):
    for x in text:
        if x==word:
            text[i]=('*' * len(x))  
    return ' '.join(text)
print censor('i have a dream','a')


@hblee12294 @javasurfer99764

You can use several different techniques to solve this problem below i have another solution to add. I have added comment's about the function so as to make it clear to what it does.


def censor(text, censor):
    This function takes a string, converts it to a list with the string function split()
    After it splits the string it searches for a match to the censor word,
    it then replaces the word with a string of '*' the correct length.
    :param text: Required as a string
    :param censor: Requires a one word string
    :return: Returns modified string
    new_text = text.split(' ')
    for word_number, word in enumerate(new_text):
        if censor == word:
            new_text[word_number] = '*' * len(word)
    return ' '.join(new_text)


You use the 'enumerate()' to make a reference for (new_text),that's good!


Thank you man, that was indeed the issue. I come from Matlab, where you only iterate with an index, so you always call up the actual element, and I assumed that writing "for x in list" would also call up the element. Good to know :smile: cheers