Using re.sub capture groups
<p>Apologies for the simple question but Im struggling with this:</p>

<pre><code>str = 'EURGBP'

print (re.sub(r'\EUR(GBP)', r'\1', str))
</code></pre>

<p>returns</p>

<pre><code>GBP
</code></pre>

<p>but</p>

<pre><code>print (re.sub(r'\(EUR)(GBP)', r'\2,\1', str))
</code></pre>

<p>gives me <code>error: unbalanced parenthesis at position 5</code></p>

<p>I am simply trying to capture both elements enclosed in parenthesis and print them out in reversed order using re like this:</p>

<pre><code>GBPEUR
</code></pre>

<p>Can someone please show me what I am doing wrong?</p>

<p>Don't escape the paren as <code>\(</code> means you are literally searching for a <code>(</code> in the string so the closing <code>)</code> has no matching opening <code>(</code>, escaping the <code>E</code> worked as you were looking for the literal <code>E</code>, also just use <code>r'\2\1'</code> unless you want them also separated by a comma:</p>

<pre><code>In [1]: import re

In [2]: s = 'EURGBP'

In [3]: re.sub(r'(EUR)(GBP)', r'\2\1', s)
Out[3]: 'GBPEUR'
</code></pre>

python