10. censor python



I have already found a great solution to this task in the forum. However I wonder why my code does not work.

Here’s the code:

def censor(text, word):
  for i in word:
    if i.isalpha() and i.islower():
        for word in text:
          word = "*" * len(word)
  return text

censor("I love you", "love")

That’s the error message:

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

Could you explain me step by step why this code fails?

Thanks in advance!


you could run your code through a visualizer:


or insert print statement to see your code in action.

what are you attempting with this line:

for i in word:

Also, this line:

for word in text:

this will give you characters/letters of text, not whole words.

word = "*" * len(word) gives us what we need to insert/replace for the words of text that needs censoring, but no censoring at all occures

censoring is generally done two ways:

replacing words in text which need censoring
creating a new string, then append word or asterisks to this new string. (uses if and else)


Thanks for your reply!
Here’s what I was attempting with these codes:

def censor(text, word): 
  for i in word: 
# Here I attempt to check if each character i of the string is an alphabetical character (isalpha) and lowercase (islower):
    if i.isalpha() and i.islower():

        for word in text:
# Here I attempt to replace each word with ***** :
          word = "*" * len(word)
  return text

But thanks to you, now I see, that it was wrong to loop like this

for word in text

since pythons loops through characters, not words.
I thought since word is defined earlier in the input _def censor (text, word). It would iterate through each word.

So python can only iterate through characters, not through variables, right?

Thanks for your reply!


text is the piece of text you want to censor
word variable contains the word you want to censor of text

so this:

for i in word: 

only loops the word you want to censor ("love" in your earlier code)

these things aren’t even related, look:

# this code would actually work if you ran it in a script
y = [3, 5, 7]
for x in y:
    print x

i define a variable x in the for loop to loop over all the values in y list. so x (or word in your case) is defined within the for loop. Just because you name it the same as an already existing variable, doesn’t change loop behavior.

python can loop through a lot of things, strings, lists, dictionaries and more.

these strings, lists, dictionaries and more can also be stored in variable. (and then we can still loop over them)


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