Trying to write code to replace/censor a word in a sentence/string. When I run it throws
Traceback (most recent call last): File "python", line 21, in File "python", line 10, in censor TypeError: list indices must be integers, not str
Here's my code:
def censor(text, word):
censored = text.split()
censoredword ="*"*len(word)
for n in censored:
if n == word:
censored[n] = censoredword
print " ".join(censored)
censor("hey baby hey", "baby")
My expected output is hey **** hey
I've tested and printed replacing sections of the split string with censored[1]= "string", printing output of censoredword for different word inputs, and I'm pretty sure I've iterated over a list in similar ways successfully, although not with replacing list items. I'm not trying to alter immutable strings in the list, simply replace a string in a list index with another.
That said, testing this:
listbegin =['hey', 'baby', 'hey']
print " ".join(listbegin)
listbegin[1] = "*"*len(listbegin[1])
print " ".join(listbegin)
returns:
hey baby hey
hey **** hey
The exercise I'm attempting to do (self study, not homework) is assuming you don't know much more than what I've used - I'm aware I can use .append, .replace, index, enumerate etc, but I'd like to know why this code is throwing an error, since it seems it's component parts function fine.
What's obvious that I'm missing here?