10/15 censor: Result keeps coming us as 'None'


Here is my code. Can you guys tell me where i’m going wrong?

def censor(text, word):
  split_text = text.split()
  censored_text = ""
  for x in split_text:
    if x == word:
      x = "*" * (len(word) + 1)
      censored_text += x
      censored_text += x
  censored_text = " ".join(censored_text)


None is the default returned value. Functions always have to return something. So a default value (None) was implemented.

you forgot to return the censored_text


Ah you’re right!

I done that, but now i get this error :

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



x = "*" * (len(word) + 1)

why +1? len() start counting at one len("hey") will return 3.

A sentence like "hey hey hey" has spaces, what happened to the spaces inside your sentence? You don’t add them anywhere in censored_text


I added the +1 because i thought it starts count at 0.

I thought censored_text = " ".join(censored_text) adds the space inbetween the words.


Wow, i really need to pay more attention

.join() is a list method, it joins a list into a string. But you already have a string, so not sure how join would behave then.


Oh i see! I thought this line here censored_text += x would add x as a list item rather than concatenate it to a string. So would it be best to ditch .join() in this case and modify censored_text += x to include the space (except for the last word)?


Okay i finally figured it out! I was doing quite a few stuff wrong :slight_smile:

I changed censored_text = "" into censored_text = [] so it’s a list and used .append() to add the words to my censored_text list.


no, because you declared censored_text as type string. += can also be use for list extending:

a = [1, 2, 3]
b = [4, 5, 6]
a += b
print a

however, when adding to a list, .append() is a better option as you figured out.

going with .append() is the better choice, if you kept censored_text you had to deal with the spaces, which is tricky


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