Censor


#1

Hi Guys,

Unsure why the below code works in notepad ++ the way it should, but not in the Codecademy window?

def censor(text,word):
    curse = " "
    phrase = " "
    text = text.split(" ")
    for i in range(0,len(text)):
        if text[i] == word:
	        curse = '*' * len(text[i])
	        phrase += curse + " "
        else:
            phrase += text[i] + " "	
    return phrase
censor("silly jerk, silly jerk", "silly")

#2

Because in you IF-ELSE loop, you inserting an extra (space) " " to the end of the string

so "Hi ****" turns into "Hi **** "


#3

Hi cody,

I inserted the spaces for formatting purposes so there is a space between words. Without the spaces it just puts everything together.


#5

stripping the leading and trailing spaces did the trick here:

def censor(text,word):
curse = " "
phrase = " "
text = text.split(" ")
for i in range(0,len(text)):
if text[i] == word:
curse = '*' * len(text[i])
phrase += curse + " "
else:
phrase += text[i] + " "
return phrase.strip()
censor("silly jerk, silly jerk", "silly")


#6

That's a cool way to do it, i like the way you've used the strip and the split methods, i hadn't come across the strip method before so i've learned something new here thanks!

Thought i'd offer that I used the 'replace' method...

def censor(text, word):
asterisks = "*" * len(word)
censored = text.replace(word, asterisks)
return censored

which may not have been the point of the exercise, perhaps we were to avoid the replace method to get a larger challenge.

Anyways thanks,
Aidy.


#7

Thanks, Aidy! Glad you got something out of this thread-- strip is definitely useful!. Your way in my opinion is best because it's concise without any extra fluff. I used the replace method as well initially, but I wasn't sure based on the directions if we were supposed to do it in that way but rather the way it was instructed. Replace makes the most sense here to me-- good stuff!


#8

I have a compact solution that seems to work well:

def censor(text, word):
    out = ""
    for i in text.split():
        if i == word:
            out += ("*" * len(word)) + " "
        else:
            out += i + " "
    return out[0:-1]

#9

def censor(text,word):
text=text.replace(word,"*" * len(word))
return text

This is not my version, but it is the shortest solution I could find and it is brilliant


#10

that looks really good, thanks for sharing! Please use the correct formatting next time, it's easy, you just need to use 3 "`" in a row at the beginning of the code block and after it.


#11

Thanks for the tip :smile: