Andrius Andrius - 2 months ago 10
Python Question

Python - merge repeating characters (ins sequence) in string?

When I have specific character that repeats more than once in a sequence, I want to merge it, so there won't be same adjacent characters.

For example:

s = 'aa.bc.a.d.aaa.z'
# after merging repeating "a" character in a sequence:


Output should be:
a.bc.a.d.a.z


P.S. I was able to find start and end indexes of such matches (with regex), but still can't see normal way of just merging those like I need.

Just to clarify how I found it:

import re
f = re.finditer('(a){2,}', s)
for match in f:
match.span()
(0, 2)
(10, 13)

Answer

You can use itertools.groupby:

s = ''.join(ch for ch, _ in itertools.groupby('aa.bc.a.d.aaa.z'))
Comments