Censor ...NEED HELP


#1

import re
def censor(text, word):
string=re.sub(word, '*' * len(word), text)
return string

This code works but I copied it. Please can someone explain the standard way of doing it. Thank you.


#2

So this is what I did:

def censor(text, word):
sentence = text.split()
length = len(word)
final_word = []
for each in sentence:
if each == word:
each = "*" * length
final_word.append(each)
else:
final_word.append(each)
return " ".join(final_word)

Basically, I take the full sentence from 'text' and split it into individual words. I then compare each word in the sentence to the censored word. If they match, the letters are replaced with asterisks and added to a list. If they don't match, the word is just directly added to the list. Finally, the list is joined together into a single string.

This may not be the shortest way to do it but it was the way that made sense in my head.


#3

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