Censor, can someone help to make up my code?


#1

Hello everyone who will see this code:) When I run my code, Python gives error:Oops, try again.Your function fails on censor("hey hey hey","hey"). It returns "******" when it should return " *** *** ***".
So, how can I make a space between same words? I used split command, but didn't understand how to put my word into that spaces.Here's my code:

s= "hey hey hey"
def censor(text,word):
    counts = []
    for letter in text:
        asterisk = len(word) * "*"
        big_letter = letter.upper()
        if letter == "":
            continue
        elif big_letter in text:
            continue
        else:
            print text.count(word)
            counts.append(word)
            counts[0:] =  asterisk
            if word in text > 1:
                word=asterisk*text.count(word)
    print text.split(word)
    return "".join(counts[0:]) 
print censor(s,"hey")

#2

One way to use .split() would be on the input string.

def censor(text,word):
    txt = text.split(" ")

or more simply, `txt = text.split()

By default, Python splits the string on spaces so none go into the list. That takes care of spaces, which we can re-introduce at the end.

I'm not clear on what the intention is with the upper case. It doesn't seem to fit the description of the problem, to censor word in text.

What we would expect to do once the list is created is iterate over the list and check each word against the parameter.

def censor(text,word):
    txt = text.split(" ")
    for i in range(len(txt)):
        if txt[i] == word:
            txt[i] = len(word) * "*"
    return " ".join(txt)

print censor("hey hey hey","hey")     # *** *** ***

Study the code above and see if it makes sense. The key here is to aim for simplicity and only do what is necessary. If the code looks complicated, it probably is doing more than it needs to. In cases like this, look for things that can be removed from the code, or that appear to serve no real purpose.

Python gives us another tool, the list comprehension. With this tool, we can reduce the above to a couple of lines:

def censor(text,word):
    a = text.split()
    return " ".join(["*" * len(word) if m == word else m for m in a])

This is doing roughly the same thing as our code above, with the same return as before.


#3

Thank you! I hope I can learn to write so cool and small codes like you! :smile:


#5

That will come with learning and practice. It will depend on a solid base of fundamentals so don't try to veer too far away from the learning material, as you could get ahead of yourself. You'll be able to spread your wings a little further with each step.


#6

A post was split to a new topic: Have no idea on how to put them toghether again


#7

A post was split to a new topic: Can't understand ... why it prints