Reputation: 75
I need to write a function that takes two strings (text and word) and returns the text with the chosen word replaced with asterisks (the number of asterisks should correspond to the number of letters in the censored word.).
For example:
if text="hey hey hey" and word="hey" the returned text should be:
'*** *** ***'
Here is my code:
def censor(text,word):
text = text.split(" ")
asterisks=[]
text_with_asterisks=[]
for item in text:
if item not in word:
text_with_asterisks.append(item)
else:
asterisks=[]
for letter in word:
asterisks.append("*")
text_with_asterisks.append(' '.join(asterisks))
return (" ".join(text_with_asterisks))
The code works but it returns:
*********
and not
*** *** ***.
Once I use the line:
return ("_".join(text_with_asterisks))
instead I get:
'***_***_***'
I don't understand why the " " is ignored and how can I add a space between the words.
Thanks!
Upvotes: 5
Views: 13462
Reputation: 95
def censor(text, censor_w):
splitted_text = text.split(" ")
asterics = "*" * len(censor_w)
result = []
for word in splitted_text:
if word == censor:
result.append(asterics)
else:
result.append(word)
return " ".join(result)
Upvotes: 0
Reputation: 1711
As text_with_asterisks.append(' '.join(asterisks))
does, each character is joined by " "
, and then " ".join(text_with_asterisks)
also makes each words joined by " "
, thus the output is: * * * * * * * * *
, where there is a space between each star.
Upvotes: 1
Reputation: 21506
Simple solution,
>>> text = "hey hey hey"
>>> "***".join(text.split("hey"))
'*** *** ***'
Or
>>> text = "hey hey they Hey','hey"
>>> " ".join([ '***' if word.lower() == 'hey' else word
... for word in text.replace("'","").replace(","," ").split()])
'*** *** they *** ***'
Upvotes: 2
Reputation: 90999
Regex method of doing this -
import re
def censor(text,word):
return re.sub(r'\b(?i){0}\b'.format(re.escape(word)),'*' * len(word), text)
Example/Demo -
>>> censor('hey hey they hey','hey')
'*** *** they ***'
>>> censor('hey hey they Hey','hey')
'*** *** they ***'
Upvotes: 3
Reputation: 42778
You have spaces between every *
in the word, and additional spaces between the words, so I think, you only want spaces between words:
def censor(text, word):
return ' '.join('*'*len(word) if word==item else item for item in text.split())
Upvotes: 2
Reputation: 13218
You have an extra space when you join your asterisks:
def censor(text, word):
text = text.split(" ")
asterisks=[]
text_with_asterisks=[]
for item in text:
if item not in word:
text_with_asterisks.append(item)
else:
asterisks=[]
for letter in word:
asterisks.append("*")
text_with_asterisks.append(''.join(asterisks)) #here's the culprit
return (" ".join(text_with_asterisks))
censor("hey hey hey", "hey")
outputs what you want ('*** *** ***'
)
I just pointed out your mistake, but surely there's a more elegant and efficient way to do what you want.
Upvotes: 3