Practice Makes Perfect: Censors


#1



Practice Makes Perfect: Censors


I'm getting this error message: "Your function fails on censor("hey hey hey","hey"). It returns "hey hey hey" when it should return "*** *** ***"."


def censor(text, word):
    words = text.split()
    for item in words:
        length = len(item)
        if item == word:
            item.replace(item, (length * '*'))
    result = ' '.join(words)
    return result


#2

I'm a little ticked that the author chose to use the variable word in the parameters. I would rather have used anything else, perhaps, term. Then we could write,

for word in words:

But, it is what it is. Just so we can have some idea that the iterator is still a word,

for term in words:

It's important to note that this is a look-up (read only) loop. We cannot alter item in the loop, or should at least not be trying to.

We can alter the list, though, if we have an index reference. But it won't be with replace(), as that is a string method.

>>> lst = ['one', 'two', 'three' ]
>>> for item in lst:
	lst[lst.index(item)] = '*' * len(item)

	
>>> lst
['***', '***', '*****']
>>>

#3

Thank you, adding the index thing worked!

So you're saying that replace() only works with strings and wasn't working in my code because I had converted the string into a list of strings? Or was it not working because the for loop was lookup only? Or both?

Also , what exactly does the index() function do? Other than enabling alteration of a list from inside a for loop obviously.

Thanks again, much appreciated!


#4

and list does not have a replace() method. If we wished to replace some part of a string in the list,

lst[indx].replace( ... )

The value (being a string) does have a replace() method.

As we saw above it returns a numeric index number of item in lst in the range 0 to len(lst) (exclusive upper bound).


#5

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