Censor


#1



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


The error message I get:
Oops, try again. Does your censor function take exactly two arguments, a text string and a word to replace with asterisks? Your code threw a "cannot concatenate 'str' and 'int' objects" error.


I can't figure out where I'm wrong in the code.


def censor(text,word):
    for i in text:
        length=len(word)
        if text[i:(i+length)]==word:
            text[i:i+length]="*"*length
    return text


#2

I see that the hint suggests using split but we didn't learn that before?


#3

your loop:

for i in text:

i will loop over your string, so i will contain a letter:

def censor(text,word):
    for i in text:
        print i
    return text
print censor("a demo of the loop", "loop")

just that you are aware of this, i are not indexes. then you need to use range()

so this:

 if text[i:(i+length)]==word:

can impossible work, since i are letters, and length is a number. so you get this for example:

"a" + 4

sorry, how is python suppose to do that math?

Are you sure this is the approach you want to use to solve this problem?

You could use split()? nothing is stopping you from checking python documentation


#4

No I think I'll use the split method. I thought maybe there was another way that I could figure out without using split. Thanks for your feedback :slight_smile:


#5

well, you could use list(), to cast the list into a list, must be possible then, but challeging i guess


#6

This one worked.

def censor(text,word):
    splittext=text.split()
    for i in range(len(splittext)):
        if splittext[i]==word:
            splittext[i] = len(word)*"*"
        new=" ".join(splittext)
    return new
    
print censor("testing out this testing method","testing")

#7

that will work indeed, well done :slight_smile:


#8

why that function work? i think the splittext[i] its not equivalent with word, because splitttext[i] its only one charachter(whether its 't' or 'e' or 's' etc) while word its a whole string ('testing'), but why it is True?


#9

splittext contains the word, look here:

splittext=text.split()

we split text into an list, the default delimiter of split is a space, so this will separate the string into a list which contains words, you can see this:

def censor(text,word):
    splittext=text.split()
    print splittext
    for i in range(len(splittext)):
        if splittext[i]==word:
            splittext[i] = len(word)*"*"
        new=" ".join(splittext)
    return new
    
print censor("testing out this testing method","testing")

#11

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