I am doing Python on Codecademy trying to censor out a word in a text. The code works but if the last word in the text has the word, it will not be censored.
I believe the for
statement needs altering such as for x in (text + 1)
but of course that causes an error. We are not to use built-in functions such as replace()
Any ideas?
def censor(text,word):
text = text.split()
for x in text:
if x == word:
text[text.index(x)] = "*" * len(word)
return " ".join(text)
print(censor("You dirty guy and dirty boy dirty.", "dirty"))
This returns [You ***** guy and ***** boy dirty.]
One of the most common methods I work with for censoring text is using dashes to remove letters whenever possible. Instead of using several dashes, most people choose to use dashes or an em dash, which looks like “—”. In addition, they typically include only the first letter or the first and last letter of a word.
It's probably including the full stop in the last token, so it is comparing "dirty."
with "dirty"
.
The last occurrence of dirty is 'dirty.'
instead of 'dirty'
.
It might be easier to use the replace
function:
def censor(text,word):
return text.replace(word, len(word)*'*')
Without built-in functions:
def censor(text,word):
while 1:
wordPosition = text.find(word)
if wordPosition < 0:
break
text = text[:wordPosition] + len(word)*'*' + text[wordPosition+len(word):]
return text
Christopher is correct that it's comparing dirty
to dirty.
with a period. As you said you cannot use replace
function, so you could change your if
statement to be
if x.startswith(word) == True:
That's due to the last dirty having .
so thus, there's difference between dirty and dirty(.). Here is a way to tackle the problem :
def censor(text, word):
wordlist = text.split()
new_words_list = []
for item in wordlist:
if item.find(word) > -1:
new_words_list.append( '*' * len(word))
else:
new_words_list.append(item)
return " ".join(new_words_list)
print(censor("You dirty guy and dirty boy dirty.", "dirty"))
Output:
You ***** guy and ***** boy *****
You can use re.sub to replace the work from text
import re
re.sub("word", "new_replaced_word", text)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With