Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to replace a word in a given sentence with a particular pattern if it's case insensitive in python?

I am given the sentence My team is the BeST team at the tournament. as a test case to create create a function

def case_insensitivity(sentence):
    return new_sentence

which checks a given sentence for a case insensitive word and replaces the case insensitive word with XXX_.

i.e.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

print(case_insensitivity('My team is the BeST team at the tournament'))
result
'My team is the XXX_ team at the tournament'

What’s the best way to do this? casefold()

>Solution :

Assuming we define the target words as having both a lowercase and uppercase beyond the first character, we can try using re.sub for a regex option:

def case_insensitivity(sentence):
    return re.sub(r'\w+(?:[A-Z]\w*[a-z]|[a-z]\w*[A-Z])\w*', 'XXX_', sentence)

print(case_insensitivity('My team is the BeST team at the tournament'))

This prints:

My team is the XXX_ team at the tournament
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading