Zak
Zak

Reputation: 1221

How to find and split a string by repeated characters?

I am trying to split a string into a list, separated by a change in character, in python. I am finding this very difficult, but am sure that I am over thinking it and missing a probably simple solution. Example:

'abgg22ffeeekkkk1zzabbb'

would become:

['a', 'b', 'gg', '22', 'ff', 'eee', 'kkkk', '1', 'zz', 'a', 'bbb']

Upvotes: 4

Views: 2220

Answers (2)

Andrew Clark
Andrew Clark

Reputation: 208475

>>> import re
>>> my_str = 'abgg22ffeekkkk1zzabbb'
>>> [m.group() for m in re.finditer(r'(.)\1*', my_str)]
['a', 'b', 'gg', '22', 'ff', 'ee', 'kkkk', '1', 'zz', 'a', 'bbb']

Upvotes: 3

Ross Patterson
Ross Patterson

Reputation: 5742

import itertools
[''.join(value) for key, value in itertools.groupby(my_str)]

Upvotes: 7

Related Questions