Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Codecademy Practice Makes Perfect 10/15 (Word Censoring)

Tags:

python

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.

like image 336
mdemont Avatar asked Jan 28 '26 23:01

mdemont


2 Answers

Change it to this:

for index, item in enumerate(wordlist):
    if item == word:
        wordlist[index] = word_now_censored
like image 147
Stefan van den Akker Avatar answered Feb 02 '26 02:02

Stefan van den Akker


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)
like image 37
BeetDemGuise Avatar answered Feb 02 '26 00:02

BeetDemGuise



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!