How can I use split( ) to make censor?


#1

Question

How can I use split( ) to make censor?

Answer

Just like join() uses the string it’s attached to to determine how to join together the string you provide in parentheses, split() does the same for splitting a string passed to it.
For example, if we have my_words_split = " ".split("first second third last"), the resulting list stored in my_words_split will be ["first", "second", "third", "last"].
We’ve done lots of work with lists, so the rest of this function is up to you, but remember to " ".join() your words back together at the end if you take this route!


FAQ: Learn Python - Practice Makes Perfect - censor
#2

A post was split to a new topic: Censor replacing using index


#3

May I know why this solution does not work? Thank you

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

  for word1 in my_text_split:
    if word1 == word:
      word1 = "*" * len(word)
  
  return " ".join(my_text_split)

#4

Because word1 contains copy of the values in list, change made to word1 won’t persist, given the loop will just assign next value in list to word1 in the following loop iteration.


#5

in one line
return text.replace(word,"".join([’*’]*len(word)))


#6

i don’t like replace, it has not the desired behavior i want from the censor function. But the exercise doesn’t have a test case for it, for example:

censor("this is a wack hack", "is")

would give:

th** ** a wack hack

I don’t think this should be partial censored, yet replace does this