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


#1

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
    else:
      censored_text += x
        
  censored_text = " ".join(censored_text)

#2

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


#3

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 " *".


#4

here:

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


#5

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.


#6

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.


#7

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)?


#8

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.


#9

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


#10

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