Replacing every occurrence of a particular word in a sentence by '*'


Hello everyone, in the exercise given by the above link where I am required to replace a particular word in a sentence by '*', I have absolutely no idea where I am going wrong.

I expect the output to be correct but it simply returns the sentence back. It would be great if someone could point out the mistake in my code. Thank you so much.

def censor(text,word):
    if word not in text:
        return text
        for i in words:
            if i==word:
                for j in range(len(i)):
                    print i
        s=" "
        return s.join(words)


but i is just a variable which exist inside the loop, the moment the loop is finished, it cease to exist

You really need to make a list/string (list is better) and appended (un)censored words to it, otherwise your work doesn't get stored anywhere. If you need more help, post an updated version of your code


Why don't you just do

def censor(text, word):
    text1 = text.replace(word, len(word)*"*")
    return text1

It's small and efficient, assuming you know the .replace()
.replace() takes two string arguments, the first it finds it in the string you want to edit, the second is the one it uses to replace the first with.

So, if word is "prep" and we print word.replace("p", "z") we will get "zrez"

Cool, huh? Now, all you have to do is have word as your first argument, a string with asterisks equal to the length of word and a string to edit, which in this case is text.


because sometimes you don't want to use build in function, to better understand algorithms.


True, as a learner you should better use your own code, and not built in functions. Thanks for replying!


then nothing gets replaced. It is good to validate inputs, but in this example it is not asked for in the instructions. No need for the if..else.

When using a lookup loop, the iterator is an immutable string, meaning we cannot change it inside the loop. It is controlled internally by Python. That's why we need a temporary object to assign values to, as alluded to by @stetim94.

    result = []
    for term in words:
        if term == word:
            result.append("*" * len(word))
    return " ".join(result)

As fun as it is to experiment with variables, it is also wasteful and hampers readability and makes debugging a lot harder. Try to work with the data items you have and only introduce variables when they are useful and necessary. The less we add to a problem, the less confusing it is.


Thank you @stetim94 for the explanation.


Thank you @digitalrunner57215 for showing me another way to solve the problem.


Thank you @mtf for making me understand the concept and showing me what I can do instead.


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