Reputation: 85
Im doing an exercise, where im defining a function that takes two inputs - a sentence and a word, that will be replaced by stars in the sentence input.
Problem is, I cant get the final output to put spaces in between words, ie it prints all the words crammed together. Any help please ?
def censor(text, word):
lis = text.split()
output =""
p = []
for w in lis:
if w != word:
p.append(w)
else:
l = len(w)
y = "*" * l
p.append(y)
output = output.join(p)
print output
censor("Hello world televison", "world")
Upvotes: 0
Views: 636
Reputation: 56
Here's another solution, even though it's a little tricky, it should handle all the different cases that can occur:
def censor(text, word):
text = '.' + text + '.'
for i in range(len(text)):
if text[i].lower() == word[0].lower():
toCensor = True
for j in range(len(word)):
if text[i + j].lower() != word[j].lower():
toCensor = False
break
if toCensor:
if (ord(text[i - 1]) < ord('A') or ord(text[i - 1]) > ord('z'))\
and (ord(text[i + len(word)]) < ord('A') or ord(text[i + len(word)]) > ord('z')):
lst = list(text)
for j in range(len(word)):
lst[i + j] = '*'
text = "".join(lst)
lst = list(text)
lst = lst[1 : -1]
return "".join(lst)
censor("World worlds world television", "world")
>>> ***** worlds ***** television
It handles capital letters and all the punctuation.
Upvotes: 0
Reputation: 2115
You don't need to initialize output
to an empty string first. You can just do
output = " ".join(p)
Notice the " ".join()
, that is what determines how you are joining your strings. In this case, it's a single space. Also, you need to return something from your function, so instead of using print
you should do
return output
Upvotes: 2