Censor


#1



So, I nearly solved the problem with the following method, but I kept ending up with one space too many. I then tried the list route and got overly frustrated with that, so now I'm back to the if loop method. I added the while loop to try to remove the space that throws off the output.


def censor(text, word):
    x = ""
    b = text.split()
    c = len(b)
    d = 0
    for n in b:
        if n == word:
            n = "*" * len(word)
        d = d + 1
        while d < c:
            x = x + (n + " ")
        else:
            x = x + n
    return x

it threw a "" error


#2

if you add a function call:

def censor(text, word):
    x = ""
    b = text.split()
    c = len(b)
    d = 0
    for n in b:
        if n == word:
            n = "*" * len(word)
        d = d + 1
        while d < c:
            x = x + (n + " ")
        else:
            x = x + n
    return x
print censor("this hack is wack hack", "hack")

you can see where it goes wrong


#3

It throws Traceback (most recent call last):
File "python", line 16, in
File "python", line 11, in censor
MemoryError

I changed
x = x + (n + " ")
to

        x = x + n + " "

& the compiler gives up suggesting there are infinite loops.

defining d =1 returns the 1st error.

I expect
c = len(b)
to = 5.


#4

you do see that the while loop is inside for loop?

each iteration of the for loop, the while loops runs


#5

solved it.

Thank you for your help.


#6