10/15 Censor - word spacing


So I nearly have this one working, here's my code so far:

def censor(text, word):
    word_list = text.split()
    ast = "*" * len(word)
    new_text = ""
    for w in word_list:
        if w != word:
            new_text = new_text + w
        elif w == word:
            new_text = new_text + ast
    return new_text

Problem is that it doesn't add in the spaces between words. I tried to add a " " to the beginning/middle/end of the statements on line 7 and 9, but becuase it doesn't know whether a word is first or last or inbetween and therefore if it needs a spcae in front or after it or both, it will always be wrong at some point - is it possible to do it using this approach, or should I be going about this in a different way?

Any help appreciated :slightly_smiling:


well, you could just add a space at the end:

new_text = new_text + w + " "


new_text = new_text + ast + " "

but this creates a problem, because then a space is also added to the last word. You could by slicing of the last character:


or you could change the string:

new_text = ""

into an array:

new_text = []

then append the word or * to the list, and then join them (see hint), hope this helps


or you could use " ".join(my_list) that actually makes a single string out of the list elements separated with " " without blank space at the end. My code is:

def censor(text, word):
    lista = text.split()
    for a in lista:
       if a == word:
           lista[lista.index(a)] = "*" * len(word)
    return " ".join(lista)


Strings are not mutable (can't be changed) so we want to avoid creating lots of strings, especially do we not want to re-create strings that we're already done with because that would get expensive with large amounts of data.

So store the words in a list and once they're all ready, join them together all in one go and as @peropero says, str.join has the added benefit of handling this little separator-nuisance for us.


Hello, your code looks like an efficient way of handling this - can you please explain the following lines of code to me?

if a == word:
splitter[splitter.index(a)] = "*" * len(word)
return " ".join(splitter)

[Edit: I used splitter instead of lista to remind me that splitter it text split into different parts]

I don't quite get [splitter.index(a)] and the code following it



I can try:
if a == word: // check if the element of the splitter list is equal to the word we looking for

splitter[splitter.index(a)] = "*" * len(word) // if it is, change it with the string of "*"s. Now, how do I find this element in the list? I need its index, right? So I use method .index() to find where in list splitter this element takes place. So my[splitter.index(a)] gives me indices of the element a.

return " ".join(splitter) returns concatenated string of list elements.

Hope this helps.