Censor error, thanks for helping, I seriously need to stop getting stuck


#1



Sorry for getting stuck again, if your're up for helping, thanks!!! 
def censor(text, word):
    words = ""
    texts = ""
    for words in text:
        if words not in text:
            texts += words
        elif words in text:
            text += "****"
    return texts

 I edited to:

def censor(text, word):
    words = ""
    texts = ""
    for words in text:
        if words not in text:
            texts += words
        elif words in text:
            text += "****"
    return texts


#2

Here's a sample version of this I just rewrote:

def censor (remove, text):
  words = text.split(" ")
  new = ""
  for word in words:
    if (word==remove):
      for i in range(len(word)):
        new+="*"
      new+=" "
    else:
      new+=word+" "
  return new

print(censor("panda", "My friends have a panda their panda is nice I like their panda very much."))

Let's go through it line by line...

  1. Define the function with two parameters; what to censor, and what to censor from (the original text)

  2. Define a words list as our original text, but split wherever there is a space, since we will ideally be working with a sentence.

  3. Defining our new string. We will add onto this each time we check the words.

  4. A for loop that iterates through each word in our words list.

  5. Checking if the word that we're on is the same as the word we want to remove.

  6. If number 5 is satisfied, we will loop however many letters the word has

  7. We will add a star to represent each censored letter to our new string

  8. We add a space, because we are finished with the word to be censored.

  9. If number 5 is not satisfied...

  10. We just add the same word to our new string, along with a space.

  11. We now return the new string, so when our censor function is called, this will be its result.

  12. A blank space to make the program pretty

  13. We print out the result of the censor function, which we provide with two parameters. The word to remove, and the sentence to remove the word from.

Questions? Let me know.

:panda_face:


Note: If you place the word to be censored at the end of a sentence with punctuation attached to it, it will not be found. There are ways to get past this error, but are not a part of this lesson. You can find a copy of code that does this here.


#3
def censor(text, string):
splittext=text.split()
resultlist=[]
    
for i in splittext:
    if i == string:
        resultlist.append("*" * len(string))
    elif not i == string:
        resultlist.append(i)
return " ".join(resultlist)

#4

Thanks. I appreciate it. I am going to try these codes.


#5

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