10. Censor, a few questions, please help


#1

So I'm doing exercise 10 and the hint suggest that we use .splt() and " ".join, and so I want to solve this using those two operators, the way that it seems that you are supposed to do it, and this is my code so far, but when I test it out on a python editor is just returns text, without word being censored.

def censor(text, word):
    a = text.split()
    b = "*" * len(word)
    for i in a:
        if i == word:
          i = b
    c = " ".join(a)
    return c

print(censor("blah is a blah", "blah"))

My main question is, how do I replace word for its "*" equivalent before joining it, that is, while it is still at list format.

and while I'm at it, how do I simply replace an item in a list with something else. I tried replace() but it seems like it only works for strings. Is there a list equivalent?

P.S.: I took a break from Python for quite a while and I decided to return and pick up where I left off, so forgive me in advance if this is a silly mistake or is there is a really simple solution that I'm missing...
THANKS :slight_smile:


#2

Hi, @isaque_lc,

Prior to the loop, create a new empty list.

Then, within the loop, inside the if block that has the header. ...

       if i == word:

... you should append b to the new list.

Create an else block. Inside that block you should append i to the new list.

Then, instead of passing a to the join method, as you have here ...

c = " ".join(a)

... pass the new list to the join method.


#3

Hey, thanks for the answer! This is my code now:

def censor(text, word):
    a = text.split()
    b = "*" * len(word)
    c = []
    for i in a:
        if i == word:
          c.append(b)
        else:
          c.append(a)
    d = " ".join(c)
    return d

print(censor("blah is a blah", "blah"))

but when I try to run it it says this:

Traceback (most recent call last):
  File "python", line 13, in <module>
  File "python", line 10, in censor
TypeError: sequence item 1: expected str instance, list found

Do you know what I've done wrong?


#4

Instead of this in the else block ...

    c.append(a)

... you should have this ...

    c.append(i)

#5

Thanks so much dude, it works now!


#6