Why does this not work? Censor


#1

def censor(text, word):
    n = ""
    j = len(word)
    text = text.split()
    for w in text:
        if w == word:
            n = n + " " + "*" * j
        else:
            n = n + w
    n = n.split()
    q = len(n)
    t = "  ".join(n)
    return t

#2

at certain point, codecademy will test your function with this code:

print censor("hey hey hey","hey")

the problem you have, is that a space is added already in the first item, i replaced the space with a underscore so you can see it:

def censor(text, word):
    n = ""
    j = len(word)
    text = text.split()
    for w in text:
        if w == word:
            n = n + "_" + "*" * j
        else:
            n = n + w
    n = n.split()
    q = len(n)
    t = "  ".join(n)
    return t
print censor("hey hey hey","hey")

This will output:

_***_***_***

it doesn't like the first space/underscore. Solution? A simple if statement, otherwise you will have to rewrite part of your program.


#3

Thank you so much :slightly_smiling:


#4

What should the if statement be???


#5

No idea, it would personally do it different, i think it would be:

if n == "":

this would check if n is an empty string


#6

then what??
please tell me what the whole if statement should be?


#7

well, it would be something like this:

if w == word:
    if n = "":
        n = # set n equal to the amount of asetrix required, this will prevent a space in the beginning
    else:
        n = n + "_" + "*" * j
else:
        n = n + w

the beauty of this exercises is to fiddle with it, this sort of problems are great to make you a better programmer