Write a function called censor that takes two strings, text and word, as input. It should return the text with the word you chose replaced with asterisks.

Error message:
Traceback (most recent call last):
File "python", line 8, in
File "python", line 5, in censor
TypeError: 'str' object does not support item assignment

I treated the string "text" as a list so I can access the individual characters. Why is that I can view them by accessing them via index, but can't alter them via index, like in line 5. How can I make my code work?

def censor(text, word):
    for char in word:
        for i in range(len(text)):
            if text[i] == char:
                text[i] = "*"
    return text
censor("hey hey hey", "hey")


They aren't lists so you can't treat them as such. Different data structures support different operations, otherwise there would only be one data structure.
You'd still have a bug even if strings were mutable - you would be changing all occurrences of 'h', 'e', and 'y', not just when they come in that order.

If you do need a list, then put the characters in a list, or the words


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