Well, first thing first, you should know that in Python, you can iterate over the words in the text and their indexes by using enumerate
. That is, you might want to do something like this:
def censor(text, word):
text = text.split()
for count, part in enumerate(text):
if part == word:
text[count] = '*' * len(part)
return ' '.join(text)
As you can see, the else
clause is not necessary anymore (it wasn't necessary before either) as we're only changing a word if the condition is met.
The above piece of code might be better re-written as a list comprehension:
def censor(list_text, word):
return ' '.join(['*' * len(part)
if part == word else part
for count, part in enumerate(list_text)])
Which you can use it like this:
print(censor('some string some other string string'.split(), 'string'))
Output:
some ****** some other ****** ******
More, in Python, the indentation should consist of 4 spaces (not 2). After each ,
you should put a space. I'd also recommend you stick to a constant censored length and avoid calculating each time how many * you should put in there.
replace
method of strings? \$\endgroup\$