Censor


#1

I don't understand why I get the following error message:

Oops, try again. Your function fails on censor("hey hey hey","hey"). It returns "hey hey hey" when it should return "*** *** ***".

def censor(text, word):
    x = text.split(" ")
    for i in text:
       for j in word:
           if i == j:
               i = "*"
               i.join(x)
    return text

print censor("c'est la merde", "merde").

To be more precise, i don't know how to use join

Can someone help me?


#2

Why nobody wants to help me ?

Is join the problem ?

What's wrong in my code?


#3

Ok now I get the following error message:

Oops, try again. Your function fails on censor("hey hey hey","hey"). It returns "" when it should return " *** ***".

This is my updated code :

def censor(text, word):
    x = text.split(" ")
    for i in text:
       for j in word:
           if i == j:
               i = "*"
               i.join(x)
               return ("*" * len(word))
    return text

print censor("c'est la merde", "merde")

I don't understand why it prints ***** altough I expect it prints c'est la *****

Can someone help me


#4

Because you wrote this:

return ("*" * len(word))

This makes your function to end and return that value. So your function cannot return the variable "text" and so your output prints only "*".


#5

Ok I tried to take into account what you say but I get the following error message:

Oops, try again. Your function fails on censor("hey hey hey","hey"). It returns "h***e***y*** he***y*** he***y" when it should return "*** *** ***".

def censor(text, word):
    x = text.split(" ")
    for i in text:
       for j in word:
           if i == j:
               word = ("*" * len(word))
    return word.join(text)

print censor("c'est la merde", "merde")

I have the impression I will never solve this problem...


#7

By nesting for loops, you're iterating over each individual letter, which is why text[i] (which equals 'h') is the same as word[j] - and since that is true, your code starts inserting "***" after each letter that matches (which happens to be all of them). Since you .split() the original text string, the new string x has items that are equal to each word. You really only need one for loop iterating over words in text and checking if each of those words is equal to word (the function's argument).

Here is one solution:

def censor(text,word):
    splittext = text.split()
    newtext = []
      
    for n in range(len(splittext)):
        if splittext[n] == word:
            stars = "*" * len(word)
            newtext.append(stars)
        else:
            newtext.append(splittext[n])
    
    result = " ".join(newtext)
        
    return result

#8

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