Why the alphabets have been separated? For censor


#1
def censor(text, word):
    text = text.split(" ")
    new_text = []
    for i in text:
        if i != word:
            new_text +=i
        else:
            i = "*" * len(word)
            new_text += i
    return new_text
print censor("ooo I am gogogo", "ooo")

the output are alphabets separated by blank.
Can anyone tell me what caused it?


#2

i don't understand your question, but this line:

new_text +=i

is a bit of a problem, it will prevent you to distinguish between the different words. I would rather use append instead, this will append the word to the list:

new_text.append(i)

(you have to do this in both if and else), and then you can use .join() to make the list into a string.

You can always add print statements inside your function, to see what is happening (which i recommend you to do in this case)


#3

well, for example, the output of above code is ***Iamgogogo,
I dont know why the word have been separated to letter(alphabets).

Besides, I am confused between + and append for adding item in list.

def censor(text, word):
    text = text.split(" ")
    new_text = []
    for i in text:
        if i != word:
            new_text +=i
        else:
            i = "*" * len(word)
            new_text += i
    return "".join(new_text)
print censor("ooo I am gogogo", "ooo")

#4

we can just see what the difference is:

def censor(text, word):
    text = text.split(" ")
    print text
    new_text = []
    for i in text:
        print new_text
        if i != word:
            new_text +=i
        else:
            i = "*" * len(word)
            new_text += i
    return "".join(new_text)
print censor("ooo I am gogogo", "ooo")

using += will just push the things into an array like a string (which is why all the spaces vanish), where as append will actually make it a proper list. The methods work very different under the hood


#5

Thank you. I think it takes time to master python....


#6

besides,
What's the different between = or in
for instance,
(1)if i in "abc"
(2)if i == "abc"


#7

that is a huge difference. if "a" in "abc" is true, since a is in abc, (so ab is also in abc, so also true) while == only is true if i is abc.


#8

what about
if "word" in "word"
and if "word" == "word"
is that equal?


#9

i am not some sort of robot to which you can endless question, why do you not simply test it?


#10

sorry,in next time I will try it first