10/15 Censor: "unsupported operand type(s) for -: 'str' and 'str'"


The problem is this line:
new_sentence = new_sentence - " "
However if I delete it the code will not pass, how do I fix this?

def censor(text,word):
    new_sentence = ""
    new_word = ""
    for i in text.split():
        if i != word:
            new_sentence += i + " "
            new_word =len(i)*"*"
            new_sentence += new_word + " "
            new_sentence = new_sentence - " "
    return new_sentence


Slicing lets you make a copy from the specified range.

'bobby'[:-2] -> 'bob'

Negative indexes wrap around on the other side and left-out arguments get default values. So the above means start at the beginning and stop before the second last value.

You may want to consider adding all the words to a list and joining them together all in one go when you're done, otherwise you are creating the whole string anew each time you "change" it. There's a string method for doing this, as a bonus it lets you specify a separator:

' is the '.join(['bob', 'best']) -> 'bob is the best'

A really neat way to solve this exercise is to split on the word to censor, and join on the asterisks!


Perfect, slicing was exactly what I needed. thank you!