Censor (using Regular Expression module)


Продолжить обсуждение из Censor 10:

Could you help me with such a variant of solution. There's an error here, but I can't identify it.

import re
def censor(text, word):
    text, word = text.lower, word.lower
    # text_len, word_len = len(str(text)), len(str(word))
    stars = '*' * len(str(text))
    new = re.sub(word, stars, text)


using regular expressions is rather difficult, why not use pythons build in replace function?


The syntax of this function is not so difficult, I thought. But nevertheless I've made an/some error(s). Would be great if someone could point the error.

Yes, I used replace function but I want to try the second solution.


i looked into the regular expressions, but i couldn't figure it out :frowning: I am sorry


text.lower and word.lower returns a function, you should use .lower() instead.

I don't know regex either, but this is working.

import re
def censor(text, word):
    p = re.compile(word, re.IGNORECASE) # compile pattern
    stars = '*' * len(word)
    new = p.sub(stars, text)
    return new
print censor("big black cat eats big Black dog", "black")
# big ***** cat eats big ***** dog