Please help me understand where my logic fails


#1


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


I found a lot of solutions to this puzzle but I want to understand where my logic fails. I would highly appreciate any help


def censor (text, word): #define a function 
    for item in text.split(): #split the text and loop through it 
        if item == word: #if we find an input word
            text.replace(item, ((len(word))*"*")) #we replace it with a number of * based on the length of it
    return " ".join(text) #return the text with replaced words


#2

you don't store the result of the replace action in a variable

.replace() will not only replace the current instance, it will replace all of them, which allows for a single line solution, bit dull

Since you are here to learn, its more fun to actually code a algorithm yourself. What you could do is create an empty list, determine if the word needs censoring, if so, append asterisks to your new list, else append the current item


#3

Thank you! I am still confused when we create a variable on a fly, like with "item" in the code below, or when we need to set up an empty list. But it still doesn't work. Based on the output it looks like something might be wrong with the join method.

def censor (text, word): #define a function 
    new_text = ()
    for item in text.split(): #split the text and loop through it 
        new_text = text.replace(item,((len(word))*"*")) #we replace it with a number of * based on the length of it
    return " ".join(new_text) #return

#4

replace does all the work for you, you don't need a list, you don't need a loop. Its a very boring solution


#5

Something like this?

def censor (text, word):  
    new_text = text.replace(word,((len(word))*"*"))
    return " ".join(new_text)

#6

But I'll try to do it the way you described and write it fully. You are right, I'm here to learn and I lack basic algorithm logic


#7

why use join()? new_text is still a string.

You should write your own algorithm.


#8

You really helped me to nail it down step by step! So sorry for stupid questions. It worked


#9

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