Howtouse.replaceinPython
I am currently learning on Codecademy and can't get past one problem:
Write a function called censor that takes two strings, text and word,
as input. It should return the text with the word you chose replaced
with asterisks.
My code is:
def censor(text, word):
word_converter = ("*" * len(word))
words = text.split()
print(words)
for bad_word in words:
if bad_word == word:
words.replace(bad_word, word_converter)
print(words)
censor("What the curseword is that", "curseword")
This is what is returned:
Traceback (most recent call last):
File "C:UsersandrePycharmProjectsfunmain.py", line 10, in <module>
censor("hello i am andrew", "hello")
File "C:UsersandrePycharmProjectsfunmain.py", line 7, in censor
words.replace(bad_word, word_converter)
AttributeError: 'list' object has no attribute 'replace'
I don't understand why the replace function does not work.
回答
The .replace syntax works on a string but not a list. You can swap an item in the list by using a pointer to the index. Updating the iteration syntax - thanks to comment from Boris
for i, w in enumerate(words):
if w == word:
words[i] = "*" * len(w)
Typically, you would build up a new list instead of altering the list you are iterating through, because changing what you are iterating on can cause problems. If you don't try replacing items in the list, you don't need the pointer.
cleaned_words = []
for w in words:
if w == word:
cleaned_words.append("*" * len(w))
else:
cleaned_words.append(w)