Censor without split & join


#1


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


I am trying to avoid using the split and join function. I managed to replace one word, how should i continue for the rest of the words?


def censor(text, word):
    replace=len(word)*"*"
    t=text
    for a in text:
        for word in a:
            if a == word:
               text= replace
            return text


#2

Hi @essamohamedali,

The str.split() method is great for utilizing delimiters, such as spaces, to divide a str into components, and the str.join() method is great for putting the parts back together. That is why they are appropriate for this exercise. However, it is fine to try another approach, as you have decided to do. If you wish to avoid using those methods, you can use the str.index() method in a loop to seek out the spaces, but it could get a little messy to handle the beginning and the end of the original str. You could also try what are called regular expressions.

Since you have decided to give the str.replace() method a try, you can dispense with a loop and simply do this ...

    return text.replace(word, len(word) * "*")

However, be aware that the above will censor not only entire words that match word, but will also censor portions of words that match it.


#3

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