Censor Dispenser - Code Review & Help with explanation

Hi guys - I am new to Python, so still trying to understand some of the logic here.
In the Censor Dispenser Challenge, https://www.codecademy.com/practice/projects/censor-dispenser
quiz for email_two, as I am working on my code, I found out the output of these two functions are very different - but none of them are entirely correct per the quiz requirement.

proprietary_terms = ["she", "personality matrix", "sense of self", "self-preservation", "learning algorithm", "her", "herself"]

def censor_more(email):
  for term in proprietary_terms:
    email = email.replace(term, "X" * len(term))
  return email

print(censor_more(email_two))

and

proprietary_terms = ["she", "personality matrix", "sense of self", "self-preservation", "learning algorithm", "her", "herself"]

def censor_more(email):
  for term in proprietary_terms:
    censored_email = email.replace(term, "X" * len(term))
  return censored_email

print(censor_more(email_two))

Why by assigning a different variable name can lead to different output result? Can someone explain the logic behind this?

Thanks so so much!

Using the the replace method of a string will provide you with an entirely new string in which instances of a certain substring are replaced with the new substring you specified. It doesn’t modify the original string.
new_string = original_string.replace(old_substring, new_substring)

By reassigning email to this new string in the first chunk of code you’ll be gradually accumulating every replacement you have performed. WIth a different name it simply makes a new string every time based only on the orirignal string reference by email. You are effectively ignoring any changes made on previous loop iterations.

Try using replace outside a loop if it’s not clear or check the docs-
https://docs.python.org/3/library/stdtypes.html#str.replace

1 Like

Thank you so much, tgrtim!