WhiteM WhiteM - 24 days ago 12
Python Question

Python,join() function, adding space between words

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!

Answer

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.