10. Censor

def censor(text, word):
    text = text.split()
    result = ""
    for words in text:
        if words == word:
            result += "*"*len(word)+ " "
            result += words
    return "".join(result)
print censor("hey hey hey", "hey")

How can I fix this? I'm so very close but there's an extra space in my code.


This is your issue right here, also get rid of the string junk you don't need it in this problem.

The ROI is

  1. Take a string
  2. Find all words to convert
  3. Replace the words
  4. Return the string

Now doing this is quite simple, your code is almost there but you have some extraneous stuff there.

def censor(text, word):
    # text = text.split() - DON'T NEED
    # result = "" - DON'T NEED
    result = [] # Create a list to hold our words that we want
    for words in text.split(' '): # Use split here with ' '  as the argument
        if words == word:
            # result += "*"*len(word)+ " " - Not needed
            result.append('*' * len(word))
            # result += words - Not needed
    return " ".join(result) # Now this works correctly, changed the string to ' '

Take a gander at your new code bit. I would also rename some parts because it becomes confusing because they are so similar.

If you still do not get any par just ask again! Cheers!


Thank you! It makes more sense now to think of the text as a "list" rather than a "string" to construct.