This works but is there a simpler way to write this?


#1

This seem a little complicated. What do you think?

def censor(text, word):
    list = text.split()
    new_list = []
    for each_word in list:
        if each_word == word:
            each_word = "*" * (len(word))
        new_list.append(each_word)
    delimiter =  ' '
    a = delimiter.join(new_list)
    return a


#2

well, you could easily reduce this 3 lines:

    delimiter =  ' '
    a = delimiter.join(new_list)
    return a

into one:

return ' '.join(new_list)

for the rest, it is quit an elegant solution, what is the problem?

of course, you could shorten it more. But it doesn't become much simpler then this, your code is nice and clean :slight_smile:

you could use replace(), it will pass the exercise, but if you then want to censor is then replace changes this into th**, and not really nice, since you don't do any coding then.

you could use list comprehension, but hasn't been taught yet.

result = [ x if x != word else "*" * len(word) for x in text.split() ]

but this is not as clean and readable as your code


#3

We are given a word that is in a sentence and we are to replace that word with a "*" character and it needs to be the length of the word itself. Essentially, we are censoring a word from the sentence. Thanks so much for you help and compliment.


#4

i know the task, and i am telling you your code is good :slight_smile:

you didn't find any of my feedback useful?


#5

Yes, it was! Thanks so much.


#6

then there are other small things you can changes, python is pretty clever:

for each_word in text.split():

but still, i think you did really well :slight_smile: your code is very readable (also very important)


#7

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