Censor- Split Decision


#1

I'm working on the Censor exercise: https://gist.github.com/e575de572a0f368b0cd2e85fbcaaa923

I've looked at a few people's code and seen different ways to do this. I'm trying to accomplish it with as little code as possible and as simply as possible. My issue is that even though I'm splitting "text" and appending it to the "phrase" list, Python is looking for the entire "phrase" list to match "word" in my "for" loop in order to censor it. I've tried moving the split around but am not having any luck. I feel like my mistake is in my implementation of the split, but I'm not sure what it is. Any suggestions?

def censor(text, word):
    text = text.split()
    phrase = []
    phrase.append(text)
    for each in phrase:
        if each == word:
            return "*" * len(word)
        else:
            return each
        return " ".join(phrase)
print censor("Hey there friend", "friend")

#2

could you explain why you did this:

phrase.append(text)

you should loop over text (given you split it into a list), then append "*" * len(word) if the word requires censoring and else just append the word (each)

then after the loop return the censored string (don't forget to convert from list to string)

also, its important to understand that the function ends the moment a return keyword is reached


#3

I think I follow you. I appended "text" to "phrase" because I wasn't thinking about the fact that splitting "text" already turned it into a list. Let me work on this a bit and report back.


#4

I'm missing something but can't figure out what. My code is producing the same results as before. It just returns whatever strings I enter as text and word. I feel like my "for" loop looks good. I'm telling it to go through each index of "text" to see if it matches "word." If so, append it with as many asterisks as the word is long. Otherwise, return the index.

def censor(text, word):
    text = text.split()
    for each in text:
        if each == word:
            text.append("*" * len(word))
        else:
            text.append(each)
        return " ".join(text)
print censor("Hey there friend", "friend")

#5

you should create an empty list before your loop, to which you are going to append the new censored sentence

after the loop has finished, join the list into a string and return it


#6

Finally got it. Thanks!


#7