0

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?

0

3 Answers 3

2

A for x in y loop is a for each loop. x will take on the value of each element in y. So in this case, x will be a string and not the index. If you need the index, you need to iterate over the integers 0 to len(censored):

for i in range(len(censored)):
    if censored[i] == word:
        censored[i] = censoredWord
Sign up to request clarification or add additional context in comments.

2 Comments

Ah! I think I'd tried in range and if censored[i] but not both at the same time, cheers!
Actually, the .replace is helpful, if I wanted to do that I'd've been looking at a much longer function.
0

Nonlinearfruit is correct. Your for...in is referring to the list items, not their index/position, so when you're going to replace, your statement censored[n] is referring to censored[hey] orcensored[baby] rather than the position of those strings in the list, and as such it's throwing the error (because hey and baby are strings, not integers indicating their position in the list).

You can also condense your code by a line:

def censor(text, word):
    censored = text.split()
    for n in range(len(censored)): <== use `range()` 
        if censored[n] == word:
          censored[n] = "*"*len(word) <== 
    print " ".join(censored)

Comments

0

In your code, n is an element of list censored. So, n is a string. You can't use n as index. Only integers are allowed for indexing.

You can do following if you want to avoid too complex approach (avoinding enumerate and all that) -

i = 0
for n in censored:
    if n == word:
        censored[i] = censoredword
    i += 1

In this way you can keep track of the index

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.