Can Someone Explain this Code?


#1
def censor(text, word):
    words = text.split()
    result = ''
    stars = '*' * len(word)
    count = 0
    for i in words:
        if i == word:
            words[count] = stars
        count += 1
    result =' '.join(words)

    return result
  
print(censor('hey guys hey', 'hey'))

Hi! I was wondering if anyone could explain this part of the code to me:

  for i in words:
        if i == word:
            words[count] = stars
        count += 1
    result =' '.join(words)

For this part, if words[count] = stars and then count += 1, if for example the text is “hey guys hey” and the word is “hey,”

Wouldn’t words[1] be replaced by stars, followed by words[2] and words [3]? Since we are only increasing the count by one. However, the code is working properly but I don’t really understand how the “count” part works.

Thanks in advance!!


FAQ: Learn Python - Practice Makes Perfect - censor
FAQ: Learn Python - Practice Makes Perfect - censor
#2

lets visualize it:

for i in words:
   print count, i

as you can see, the code is smartly crafted to use count as indexes for the different items in list.

the reason guys doesn’t get replace is because i == word is false (“guys” == “hey”), so words list doesn’t get updated.

remember, this:

words[count] = stars

updates elements in list (words) using integers/indexes (count).


#3

Thank you! Could you explain why this wouldn’t work then?:

def censor(text, word):
    words = text.split()
    censored = "*" * len(word)
    for n, i in enumerate(words):
      if i == word:
        words[n] == censored
    return " ".join(words)

instead of using the count as an index, i used the enumerate function. But the code doesn’t seem right ><


#4

enumerate is available, so that is then easier to use. I would give more logic variable names (index and value, not n and i)

here:

words[n] == censored

you do a comparison to check if these values are equal, not sure why. You should update the list element with asterisks.


#5

hey man! Thanks for the speedy replies and help! You are fantastic!


#6