Skip to content
Advertisement

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.

Advertisement

Answer

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"bexampleb(?=([^`]*`[^`]*`)*[^`]*$)", "EXAMPLE", s)
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement