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

Capitalize words in string except for ones in quote

I want to capitalize keywords in a list of strings except for keywords that are in quote.

let’s say you have

list1 = ["I like bananas", "he likes 'bananas' and apples", "we like bananas and apples"]
list2 = ["bananas", "apples"]

the output I’d want is

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

>>> ["I like BANANAS", "he likes 'bananas' and APPLES", "we like BANANAS and APPLES"]

>Solution :

You can use regular expression to check if the phrase in list2 is surrounded by quotes or not:

import re

In [ ]: re.sub(rf"(?<!')bananas(?!')", "BANANAS", "I like bananas")
Out[ ]: 'I like BANANAS'

In [ ]: re.sub(rf"(?<!')bananas(?!')", "BANANAS", "I like 'bananas'")
Out[ ]: "I like 'bananas'"

You can create function to replace all patterns in list2:

def capitalize(s, pats):
     for pat in pats:
         s = re.sub(rf"(?<!'){pat}(?!')", pat.upper(), s)
     return s

In [ ]: [capitalize(s, list2) for s in list1]
Out[ ]:
['I like BANANAS',
 "he likes 'bananas' and APPLES",
 'we like BANANAS and APPLES']

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