Censor: adding space between words


#1

https://www.codecademy.com/en/courses/python-intermediate-en-rCQKw/1/4?curriculum_id=4f89dab3d788890003000096#

Oops, try again. Your function fails on censor("hey hey hey","hey"). It returns "******" when it should return " *** ***".

The loop works but I cannot figure out how to insert a space between words...


def censor(text,word):
    new_text = text.split()
    result = ""
    for words in new_text:
        if words == word:
            result += "*" * len(word)
        else:
            result += words
    return "".join(result)

#2

look at join:

return "".join(result)

the character(s) between the two quotation marks (") is what join uses to join the items together, so for example:

return "-".join(result)

would result in:

***-***-***

with this knowledge, you should be able to solve your problem.


#3

I tried this before and it returned: * * * * * * * * *
I solved the problem in the end by using lists but I would like to understand if it is still possible doing it without converting my str into a list.


#4

i didn't even look at this, i assumed because you use .join() you used lists.

well what you could do is this:

if words == word:
    result += "*" * len(word) + " "
else:
   result += words + " "

this only gives one problem, lets replace the spaces with underscores:

***_***_***_

you have a additional space at the end, you could slice it off ([:-1])

i however, do not recommend this solution. you can't manipulate strings, every time you use += a new string has to be made to store the result of the joining. This is an expensive operation


#5

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.