Censor


#1

Your function fails on censor(“hey hey hey”,“hey”). It returns “hey hey hey” when it should return “*** *** ***”.



def censor(text,word):
  for item in text:
    if item==word:
      item='*' * len(word)
  return text



#2

item contains read-only values from the list, any changes made to it won’t persist

you will need to find a way to make the change persist


#3

How about this? It does not say in the task not to use in-built function? “replace” (just as it says not to some other in the previous tasks …).

def censor(text, word):
for k in text:
if word in text:
new_word = len(word) * “*”

print text.replace(word, new_word)

#4

Or even shorter:

def censor(text, word):
for k in text:
k = len(word) * "*"
return text.replace(word, k)


#5

using .replace() is not forbidden, but it doesn’t teach you much, that is your choice.

besides that, .replace() isn’t perfect, lets say we want to replace all is in sentence, using replace() also will censor this to th**


#6

I use the string.split().How can I return it as a string after I split it?And the change still can’t persist.

Your function fails on censor(“hey hey hey”,“hey”). It returns “[‘hey’, ‘hey’, ‘hey’]” when it should return “*** *** ***”.

def censor(text,word):
  text=text.split()
  for item in text:
    if item==word:
      item='*' * len(word)
  return text

#8

we could use .join() to join list into string. If you want to go for this approach, you need range() in your for loop so you can update the elements in your text list when they need censoring

range gives us indexes, indexes can be used to update elements in list


#9

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