简体   繁体   中英

Replacing string in list of non-empty strings

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?

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

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

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 ] or censored[ 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM