Censor help


code works if the “word” bit is only one letter but anything above one letter just leads to it replacing every instance of the letter with an * regardless on if its in that order or not. what would i have to do to fix this specific problem. also i had a look at the default answer and had no clue what it was using, it was using inbuilt functions ive never seen eg. .split() and .join()

<do not remove the three backticks above>
def censor(text, word):
  line = ""
  for x in text:
    if x in word:
      x = "*"
      line += x
      line += x
  print line
  return line


Hi @mikeylive98 I will help you refactor your code so it looks clean and concise.
Firstly, .split() is a method that converts a string to a list according to it’s whitespace.
And .join() converts that list back to a string.

  • define a function called “censor” that takes two parameters

  • define a variable that holds a list

  • define a variable that splits the text parameter

  • loop through the split text and use an if conditional to see if it matches the word

  • if so, append that to the list with the number of astericks corresponding to the length of the word

  • if not, just append the text (remember it’s the for looping variable/placeholder)

  • return using the join method on the list

  • call function

Hope this helps :smiley:


thats my problem here i cant seem to get my code to recognise the filter as a word , it only recognises it as individual letters.

eg. censor( hi im michael , im )
would give me “h* ** **chael” instead of the desired "hi ** michael"
how to i make the code recognise the “im” as a word and not two individual letters?


Good thing it doesn’t recognize bad grammar.

None of the arguments is a string.

censor("Hi, I'm Michael.", "I'm")


very funny, although correcting grammar helps in that specific instance it still doesn’t solve my problem, how do i make it recognise the “word” as a string, is there any way of making my code as it stands work, i;'d rather not have to copy the default answer it seems complicated compared to this.


For starters, treat text as a phrase, not a simple character string. That means we need to split it to break out the words in the phrase.

text = text.split()

Now iterate over the list that results.

for term in text:
    if term == word:

Before the loop it will be helpful to initialize an empty list.

result = []

Now inside the conditional, append one of term or '*' * len(word) to that list. return the joined result when the loop is completed.


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