I did earlier say that
string.replace() took all the fun out, which in the case of seeking an algorithm, it does but that is not entirely the case. We can have fun with it, but in a different approach that veers away to anonymous procedure
>>> censor = lambda x, w: x.replace(w, len(w) * '*')
>>> censor("hey hey hey", "hey")
'*** *** ***'
Now we can re-use this expression to censor a list of words from a block of text.
def censored(x, s):
for h in s:
x = censor(x,h)
print (censored("hey you, get off the nice grass",['you','nice']))
# hey ***, get off the **** grass
With a minor tweak we can use this function for all instances, list or word. We'll straighten out the dependency issue as well.
def censor(x, s):
swap = lambda x, w: x.replace(w, len(w) * '*')
for w in list(s):
x = swap(x, w)
It is clear that this exercise is gearing us up for bigger challenges and also opening some doors. Worth the time spent.