Censor


#1



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


Oops, try again. Your function fails on censor("hey hey hey", "hey"). It returns "******" when it should return " *** ***"


Please help me figure out why this happens when I made code for the spaces.


 def censor(text, word):
    ntext = text.split()
    script = ''
    for i in ntext:
        censored = '*' * len(i)
        while i in ntext < len(ntext) - 1: #code to check if there can be spaces
            if i == word:
                script += censored + ' '
            else:
                script += i + ' '
        else: #if there should not be any spaces
            if i == word:
                script += censored
            else:
                script += i
    return script
print censor('hey hey hey', 'hey')


#2

Hard to tell when the error message has been misinterpreted by the forum's markup, put it in backticks so that it's preserved exactly

Running your code though, shows that there are no spaces between. You say you wrote code for handling the spaces, so if they aren't there then it's either not doing its job or it doesn't run at all. You can determine which is the case by adding a print statement which would only show up in the console if that part of the code does run. If it doesn't, then you've determined that the problem is with the condition for running that, or if it does, then you've determined that it isn't doing what it should. After that you've got much less code that you need to consider.
Also note that you've got a while-else statement, I suspect that you don't know what that does, so you probably shouldn't have it in your code either (only use things that you can reason about)


#3

I ran a print statement, as seen at the bottom of the code. The code for spaces doesn't seem to work, which is why I am asking for help.


#4

you can make it far simpler by using these three lines:


def censor(text, word):
if word in text:
return text.replace(word, ("*" * len(word)))


By using .replace(), it replaces anything in the string with anything.


#6

`def censor(text,word):
    str1 = text.split(' ')
    str2 = []
    for item in range(len(str1)):
        num = str1.index(word)
        length = len(str1[num])
        if str1[item] == word:
            str2.append("*" * length)  
        else:
            str2.append(str1[item])
    return  " ".join(str2)
    
print censor("what the fudge is that","fudge")
    `

try this code


#7

There were still things you could do yourself first, both to bring yourself closer to solving it yourself and to improve your question


#8

Now this is what I call true programming, shortening the code while still keeping it very clear and understable, good one :slight_smile:


#9

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