10: Censor


#1




Returns saying that the code doesn't work with "hey, hey, hey", "hey". I think it may have something to do with the split command. -_-


The split(), as far as I know, should split up each word in the argument into a list. I could be wrong however and this may be why my code is not working. What does the split() command actually do? Any help would b e great thanks :slight_smile:


def censor(text, word):
    sentence = text.split()
    for w in sentence:
        if w == word:
            w = "*" * len(word)
    return " ".join(sentence)
print censor("This is hecking brilliant", "hecking")


#2

Yes, you're right! the .split() command splits the original string into separate strings of each word into a list. You can test this out by doing print sentence in your code to see that list printed in your console.

As for why your code isn't satisfying the problem, you haven't looped through your sentence list to find the index of the word and replace it with your censored version. Currently, you are returning the whole sentence as it was without implementing your censor change.

The way I did this was by creating an empty list outside of my loops and used for index, string in enumerate(sentence) to .insert(index, string) into the empty list.

Also mentioned in an earlier Q&A about "Censor," you cannot change your iterator, w, to equal something else. You'll need to make a new variable to save the censored version of your word to be able to insert it.

Hope I helped a little!


#3

@codeninja16848 can you share your code here please? would be helpful to see how enumerate works in this case..


#4

Of course. Here's how I did it.

def censor(text, word):
    split_text = text.split()
    censored = []
    
    for index, string in enumerate(split_text):
        if string == word:
            censored_word = "*" * len(word)
            censored.insert(index, censored_word)
        else:
            censored.insert(index, string)
 
    return " ".join(censored)

With enumerate, just as you'd do for word in sentence, it incorporates the word's index as well. This means that when we insert our censored word, we can simply tell it to insert it as the same index it was originally at.


#5

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