Censor


#1

Hi, guys! I decided to not follow the recommendations in the hint attached to this exercise and do this task on my own way, but I don't understand why this code doesn't work.This function returns the same string that was inputted without any replacement((( Could anyone explain it to me? Thanks in advance.

def censor(text, word):
    text = text.lower()
    if word in text:
        for e in word:
            e = "*"
    return text

#2

We cannot mutate a string.

Not sure we can even do this with strings. text needs to be split() into a list of words.

words = text.split()

for instance. Now we can iterate over the list of terms,

def censor(text, word):
    words = text.split()
    for i in range(len(words)):
        if words[i] == word:
            words[i] = "*" * len(word)    # here we mutate an indexed element
    return ' '.join(words)

Of course there are simpler ways. This only demonstrates mutating a list.


#3

Thanks you a lot. But it's strange to me that it's impossible to iterate through a string, because the string is a set of characters, and I thought that it's possible to iterate through string.


#4

Iterate, yes, mutate, no. Strings are indeed iterable, much like lists, but to mutate a string requires concatenating slices to build a new string. Not that difficult, and worth exploring, for sure. That's how you will find some of the other approaches to this problem, by playing with it.


#5

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