10.censor


#1

Hi! Im getting this error : Does your censor function take exactly two arguments, a text string and a word to replace with asterisks? Your code threw a "list indices must be integers, not str" error.
I will appreciate any help :smiley:


def censor(text,word):
    text_str=""
    text_list=[]
    text_list_switched=[]
    a_count=len(word)
    text_list=text.split()
    for n in text_list:
        if str(text_list[n])==word:
            text_list[n]=a_count * "*"
    return text_str.join(text_list)


#2

n in this construct is a string, not an integer. To iterate by index, use range().

However, now that we know n is a word, we may compare directly to word.

This line is redundant. .split() returns a list object.

Also redundant. A literal separator in a .join() expression is more explicit, imho.

If you do not want to make repeat calls to len() then call it once and build a replacement text string in one action.

repl = len(word) * "*"

Since n is not an integer, we cannot write to the list. However, we can append it:

    if n == word:
        text_list.append(repl)
    else:
        text_list.append(n)

#5

Thank you for your feedback. Im purposefully ignoring your redundancy corrections, because I want to get the code going first and then refine it. So what I ended up with is

def censor(text,word):
text_str=""

text_list_switched=[]
a_count=len(word)
text_list=text.split()
for n in range(len(text_list)):
    if str(text_list[n])==word:
        text_list_switched.append(a_count * "*")
    else:
        text_list_switched.append(n)
return " ".join(text_list_switched)

and error: "sequence item 0: expected string, int found"
So as Im posting this I substitued text_list_switched.append(n) with ....append(text_list[n]) and it DID work. For some reason your suggestion of doing it the shorter way didn't. Thank you for your help! :slight_smile:


#6

Read my reply again.

for n in range(len(x))    # x is a list

n is an integer, a counting number and index, x[n] is the value.

for n in x

n is a string, it is the value.