Replace in string with alternation
<p>I want to replace <code>##</code> with <code>&lt;&lt;</code> and <code>&gt;&gt;</code> with alternation. For example <code>abc##123##qwe##asd##</code> to <code>abc&lt;&lt;123&gt;&gt;qwe&lt;&lt;asd&gt;&gt;</code>. Of course I can read symbols one by one, check them, do the replace to <code>&lt;&lt;</code> if it's even time or to <code>&gt;&gt;</code> if it's odd time. But there is power collection of standard functions in Python so I wonder if I can use them to reduce my code.</p>

<p>you can use following statement to change only pair of <code>##</code> and leave non-matching <code>##</code> as it is</p>

<pre><code>d = "abc##123##qwe##asd"
re.sub(r'(##)(.*?)(?(1)##)', r'&lt;&lt;\2&gt;&gt;', d)

# 'abc&lt;&lt;123&gt;&gt;qwe##asd'
</code></pre>

<p>or you can do this</p>

<pre><code>re.sub(r'(##)(.*?)(?(1)##)', r'&lt;&lt;\2&gt;&gt;', d).replace("##","&lt;&lt;")

# 'abc&lt;&lt;123&gt;&gt;qwe&lt;&lt;asd'
</code></pre>

python string replace