Censor (using Regular Expression module)


#1

Продолжить обсуждение из 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)
    return(new)

#2

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


#3

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.


#4

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


#5

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