Extra Study –
Enumeration is the act of creating a special object that consists of index - value pairs. A list of tuples is what it generates.
>>> print list((enumerate([5, 8, 13, 21, 34, 55])))
[(0, 5), (1, 8), (2, 13), (3, 21), (4, 34), (5, 55)]
We don’t need the list, just the object. It allows us to iterate it for both index and value, which is pretty handy in this problem and many others you will encounter going forward. When we want both the index and the value, it is worth the investment.
>>> def censor_(text, word):
t = text.split()
r = range(len(t))
s = '*' * len(word)
for i, x in enumerate(t):
if x == word:
t[i] = s
return ' '.join(t)
>>> censor_('hey hey hey','hey')
'*** *** ***'
>>> censor_('text text text text', 'text')
'**** **** **** ****'
>>> censor_('the password is 12345','12345')
'the password is *****'
I’m a big fan of simple symbols. The first three lines of the function contain all the clutter, and they are all self-described. We don’t need bulky names for these transient variables, imho.
By the time we get to the loop we know what everything is, and the rest is just mechanics. The space character is only in the return statement and nowhere else in the code so I opted for using the literal in the expression.