Censor


#1

NEED HELP . CAN'T FIGURE OUT WHERE I AM GOING WRONG . MY CODE IS AS FOLLOWING :-

def censor(text,word):
    new_string = []
    text = text.split()
    n = len(word)
    c = len(text)
    m = "*" * len(word)
    for i in text:
        if i == word:
           new_string.append(m)
        print " ".join(new_string)    
    return new_string        
print censor("this is hack", "hack")

WHEN I RUN IT GIVES THE FOLLOWING ERROR MESSAGE :-
Oops, try again. Your function fails on censor("hey hey hey","hey"). It returns "['', '', '']" when it should return " *** ***".


#2

if you want to do this approach, you will need to add else to append words which do not require censoring to new_string

then after the loop, join the list into a string and return the string


#3

 if i == word:
           new_string.append(m)

After this you need to introduce else statement that will take care of those words which are not going to be censored!

hint**
You need to append them inside the list.

Also...
You're not using variables c and n


#4

Okay: we can try to step through what you have posted:

def censor(text,word):
    
    new_string = []     # new_string isn't a string, it's an array
    text = text.split() # okay, now text is an array of strings
    n = len(word)       # n is the length of the ‘word‛ argument
    c = len(text)       # c is the number of words in the original ‘text‛ argument
    m = "*" * len(word) # m is a string of stars, as long as the ‘word’ argument
    for i in text:      # i is a word in the original text
        if i == word:
            new_string.append(m)    # add a string of stars to new_string array
                        # not doing anything with words that don’t match ‘word’?

    print " ".join(new_string)  # no need to do any printing within the function
    return new_string   # return an array of strings of stars
                        # n and c are never used

print censor("this is hack", "hack")    # this will print “["****"]” because the 
                                        # function returns an array of strings

Try thinking about it in these steps:

  1. use an array to split the text into words (you did that)
  2. for each word, if it matches the 'word' then replace it with stars (you did that)
  3. if it doesn't match, remember to keep the original word (you didn't do that)
  4. join the array back up into a string (you did that)
  5. return the string (you didn't do that)

Hope that helps?

Tim F


#5

4 posts were split to a new topic: [solved]censor


#6

THANKS BUDDY FOR POINTING OUT THE PROBLEM . :slight_smile:


#7

THANKS MAN FOR POINTING OUT THE PROBLEM . :slight_smile:


#8

THANKS FOR POINTING OUT THE PROBLEM OF RETURNING THE NEW STRING:slight_smile:


#9

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