mdemont mdemont - 4 months ago 173
Python Question

Codecademy Practice Makes Perfect 10/15 (Word Censoring)

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.

Answer

Your observation is right

changing the value of item in the for loop doesn't change the value of the item in the list.

There are many ways to go about this. Here is one way. Create another variable new_words_list. Append the word from wordlist to new_words_list if it not word. Else append word_now_censored to new_words_list.

Which translates to:

def censor(text, word):
    length_of_word = len(word)
    word_now_censored = '*' * length_of_word
    wordlist = text.split()
    new_words_list = []
    for item in wordlist:
        if item == word:
            new_words_list.append(word_now_censored)
        else:
            new_words_list.append(item)

    return " ".join(new_words_list)