'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.
Solution 1:[1]
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)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | trincot |
