Looping over a string


#1
def censor(text, word):
  result = ""
  text = text.lower()
  for x in text:
    if x == word:
      result = result + "*" * len(word)
      return result
      break
    else:
      result = result + text
      return result

I am wondering why this version is not working? When the input is “hey hey hey”, “hey”. it prints hey hey hey to the console instead of censoring it


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

there are a couple of problems with your code.

looping over a string will give characters not whole words:

for letter in "hello world":
   print letter

which in your case means x contains individual letters/characters, which will never equal word if word has more then one character (which is very very likely)

break will break the loop, so then the loop ends, that means the first word get censored, the rest doesn’t. Which is problematic if the sentence contains word multiple times, which is also a strong possibility.

return is even worse, return is the last thing a function does (none by default at the end of the function), so when a return keyword is reached, not only does the loop end, the whole function ends!