Censor Dispenser Email 2

Hello, I’m currently not getting the desired output from my 2nd function, however my first function which is very similar does give the correct output, so I am unsure where I’m going wrong.

Here is my first function that does give the correct output:

def censor_word(text, word):
   return text.replace(word, '_____')

print(censor_word(email_one, 'learning algorithms'))

And here is my 2nd function that is currently returning the full text of email_two but does not censor the specified words:

def censor_words(text, words):
  text_copy = text
  for word in words:
    text_copy.replace(word, '_____')
  return text_copy
print(censor_words(email_two, proprietary_terms))

I added the print(word) call into the function to verify that I am getting the correct inputs, and I am, but they are not being replaced in text_copy.
Any help is appreciated.

Here’s a hint example:

text = "hello how are you"

text.replace("hello", "hi")
#this returns: 'hi how are you'

#now this outputs: 'hello how are you'

Do you see where this could go wrong?

But shouldn’t text_copy be updated when iterating through the list since it is contained within the function?

I’m just observing what happens when I interact with the method like that…

Documentation confirms this by saying it only returns a copy of the string. It doesn’t say anything about modifying the variable or string it gets the string from.

str. replace ( old , new [, count ])
Return a copy of the string with all occurrences of substring old replaced by new . If the optional argument count is given, only the first count occurrences are replaced.

From python documentation: https://docs.python.org/3/library/stdtypes.html#str.replace

It’s a very common occurrence for me to get even a common operation to work not as intended. All that means is that it’s an opportunity to go to the docs and pick up a wrinkle of nuance as to how it works.

I think I understand. I will reply back once I fix it.
Thank you

def censor_words(text, words):
  text_copy = text
  for word in words:
    text_copy = text_copy.replace(word, '_____')
  return text_copy

print(censor_words(email_two, proprietary_terms))

Fixed it. :slight_smile: Thanks again

1 Like

Nevermind perfect! lol. I need to think before I write. :rofl: :sweat_smile: :sweat_smile: :sweat_smile: @fattone225

1 Like