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 do you perform an operation on a phrase *only* if it's outside backticks?

E.g. say you have the line:

`Here's an example.` And another example.

How could you change only the second "example" to uppercase? E.g:

`Here's an example.` And another EXAMPLE.

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

>Solution :

You could split by backtick and then make the replacement in the even indexed chunks:

s = "`Here's an example.` And another example."
res = "`".join(part if i % 2 else part.replace("example", "EXAMPLE") 
                  for i, part in enumerate(s.split("`"))
              )

Or, with a regular expression you could look ahead and only make the replacement when the number of backticks that follow it, is even:

import re

s = "`Here's an example.` And another example."
res = re.sub(r"\bexample\b(?=([^`]*`[^`]*`)*[^`]*$)", "EXAMPLE", s)
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