I'm on Codecademy, the section called "Practice Makes Perfect", on problem 10/15, the word-censoring one. The problem goes like this:
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 idea was to do this:
def censor(text, word):
length_of_word = len(word)
word_now_censored = '*' * length_of_word
wordlist = text.split()
for item in wordlist:
if item == word:
item = word_now_censored
return " ".join(wordlist)
But, so it seems, changing the value of item in the for loop doesn't change the value of the item in the list.
I thought another way could be to use a while loop, going from i = 0 to i < len(wordlist), and then modify wordlist[i] as needed, but I'd just like to understand why my for-loop method doesn't work.
Change it to this:
for index, item in enumerate(wordlist):
if item == word:
wordlist[index] = word_now_censored
You could simply use re.sub to replace all instances of word:
import re
def censor(text, word):
return re.sub(r'\b{}\b'.format(word), '*' * len(word), text)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With