Andrius Andrius - 1 year ago 75
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 = ''
# after merging repeating "a" character in a sequence:

Output should be:

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:
(0, 2)
(10, 13)

Answer Source

You can use itertools.groupby:

s = ''.join(ch for ch, _ in itertools.groupby(''))