Strange for loop in "censor"


#1



https://www.codecademy.com/courses/python-intermediate-en-rCQKw/1/4?curriculum_id=4f89dab3d788890003000096


So this function is indeed censoring the word it is supposed to, but it only ever loops that one word. Meaning that it should append 'Hi' in it's first itteration, but instead it returns 'arse' which it then continues to censor in a second iteration to change it to '***'. I've added the pint commands to check on the list. It seems to be in order, so I suspect something went wrong with the for loop. Any help is appreciated :slight_smile:

The output:

['Hi', 'arse']
['arse', '****']
arse ****


def censor(text, word):
    words_in_text = text.split()
    censored_text = []
    
    print words_in_text

    for w in words_in_text:
        if w == word:
            censored_text.append('*' * len(word))
        else:
            censored_text.append(word)
    phrase = " ".join(censored_text)
    print censored_text
    return phrase

print censor("Hi arse", "arse")


#2

it does? if you place the print at the correct place:

def censor(text, word):
    words_in_text = text.split()
    censored_text = []
    for w in words_in_text:
        if w == word:
            censored_text.append('*' * len(word))
        else:
            censored_text.append(word)
        print censored_text
    phrase = " ".join(censored_text)
    return phrase

print censor("Hi arse", "arse")

you see hi being append first, i don't see the problem?


#3

Hi Stetim,

thanks for the quick answer. However, running the code you proposed with the print command actually returns something different. Now there's no 'Hi'' at all anymore. I swear, this is some seriously weird code.

['arse']
['arse', '****']
arse ****
None


#4

i am blind, sorry, here:

censored_text.append(word)

you append word, but word contains the word you want to censor, why append it your list here? You actually want to append the word that doesn't require censoring


#5

OMG, yes. I wanted to append w not word. You're right. That' fixed it, when I replace word with w. Thank you so much, Stetim :slight_smile:


#6

well, you know understand where you went wrong, everything should be clear?


#7

Yes, everything is clear. It was a stupid mistake in an otherwise hopefully good code :slight_smile:


#8

good to hear. Yea, i think this is a good solution to this problem :slight_smile:


#9

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.