10. censor

it print an asterisk just for the first word

Replace this line with your code. 
def censor(text,word):
    word= word+len(word)
    for word in text:
        return text


First problem is the placement of return. It is inside the loop rather than after it.

Second, str.replace does not need a loop, since by default it is greedy. As I've said before, however, this exercise is not about finding the best built-in function, but writing an algorithm to solve the problem, without the use of built-ins.

Not sure what that line is expected to produce. We cannot add a number to a string, except as string data. The only place where length figures into this is in how many asterisks to write.

len(word) * "*"

word is a locally defined parameter that this overwriting. Choose a different variable, like, term, perhaps.


it looks like I need a better understanding of this ,where I could find something that it helps me to solve this problem


Peruse the forums, for one, although that might be too easy as there are a lot of near solutions (and some complete) posted there.

Break down the problem. Given a phrase such as a sentence or block of prose text, and a word to redact from it, how might we cycle through the phrase to look for the word?

Hint: In Python, strings are immutable so it is very likely we would convert the phrase to a list, first.

text = text.split()

This will create a list of just the words, no space characters. Now we can cycle through the list and compare each term to the word. It follows that we will have initialized a temporary list to take our interim results at each step, either the term being accepted, or the replacement with *'s.

At the completion of the loop, return the list as a string, using join().


thanks I will try that


Hmm, I am afraid that I struggled and in the end I used the enumerate statement/command that enabled me to combine the positions of/and the word I needed to remove. That worked but a bit lengthy


Something like this, perhaps?

>>> text = "The rain in Spain falls mainly on the plains."
>>> word = 'rain'
>>> text = text.split()
>>> for i, x in enumerate(text):
    if x == word:
        text[i] = "*" * len(word)

>>> text
['The', '****', 'in', 'Spain', 'falls', 'mainly', 'on', 'the', 'plains.']
>>> ' '.join(text)
'The **** in Spain falls mainly on the plains.'


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