Two ways to do this, either capture your pre- and post-fixes, or use lookbehinds and lookaheads.
# captures = "Example {String}"replaced = re.sub(r'({).*?(})', r'\1a\2', s)# lookarounds = "Example {String}"replaced = re.sub(r'(?<={).*?(?=})', r'a', s)
If you capture you pre- and post-fixes, you're able to use those capture groups in your substitution using \{capture_num}
, e.g. \1
and \2
.
If you use lookarounds, you essentially DON'T MATCH those pre-/post-fixes, you simply assert that they are there. Thus the substitution only swaps the letters in between.
Of course for this simple sub, the better solution is probably:
re.sub(r'{.*?}', r'{a}', s)