Python Forum
Case Insensitive Censor Function
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Case Insensitive Censor Function
#4
When I wrote my post yesterday I was pretty tired. Maybe an explanation is in place.

The "IGNORECASE" flag is pretty obvious, it secures matching regardless of case, the "escape" function escapes all special characters in the pattern "i", if any. I would maybe use better names, but that is mostly left to personal taste.
You can use other flags and combine them with "|" (bitwise OR). It is unicode safe unless you specify a langauage or ASCII flag. Best to consult https://docs.python.org/.

I tested it this morning:
>>> import re
>>> def censor2(text, banned):
...     for i in banned:
...         replace = re.compile(re.escape(i), re.IGNORECASE)
...         substitute = '*'*len(i)
...         text = replace.sub(substitute, text)
...     return text
>>> print(censor2('Hello World, hElLo IDIOT, HeLlO', ['hello', 'idiot']))
***** World, ***** *****, *****
>>> 
HNiChuimin likes this post
Reply


Messages In This Thread
Case Insensitive Censor Function - by HNiChuimin - Jan-14-2021, 12:10 PM
RE: Case Insensitive Censor Function - by Larz60+ - Jan-14-2021, 08:38 PM
RE: Case Insensitive Censor Function - by Serafim - Jan-14-2021, 11:13 PM
RE: Case Insensitive Censor Function - by Serafim - Jan-15-2021, 08:20 AM
RE: Case Insensitive Censor Function - by Serafim - Jan-16-2021, 12:13 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  List Censor Thread palmtrees 6 7,104 Oct-05-2016, 06:22 PM
Last Post: nilamo

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020