Remove only double letters sequences in word with best speed with python
<p>Very popular task for finding/replacing double letters in a string. But exist solution, where you can make remove double letters through few steps. For example, we have string <code>"skalallapennndraaa"</code>, and after replacing double letters we need to get in output <code>"skalpendra"</code>. I tried solution with </p>

<pre><code>re.sub(r'([a-z])\1+', r'\1', "skalallapennndraaa")
</code></pre>

<p>, but this don't remove all double letters in a string(result- <code>"skalalapendra"</code>). If I use <code>r''</code> as second parameter, I got a closely related result <code>"skalaapendr"</code>, but I still can't find right regular expression for replacement parameter. Any ideas?</p>

<p>You can use this double replacement:</p>

<pre><code>&gt;&gt;&gt; s = 'skalallapennndraaa'
&gt;&gt;&gt; print re.sub(r'([a-z])\1', '', re.sub(r'([a-z])([a-z])\2\1', '', s))
skalpendra
</code></pre>

<p><code>([a-z])([a-z])\2\1</code> will remove <code>alla</code> type of cases and <code>([a-z])\1</code> will remove remaining double letters.</p>

<hr>

<p><strong>Update:</strong> Based on comments below I realize a loop based approach is best. Here it is:</p>

<pre><code>&gt;&gt;&gt; s = 'nballabnz'
&gt;&gt;&gt; while re.search(r'([a-z])\1', s):
...     s = re.sub(r'([a-z])\1', '', s)
...
&gt;&gt;&gt; print s
z
</code></pre>

python regex string