How to find and break a string with repeated characters?

I am trying to split a string into a list, separated by a character change, in python. I find it very difficult, but I'm sure I stopped thinking about it and skipped a possibly simple solution. Example:

'abgg22ffeeekkkk1zzabbb'

will become:

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

+3
source share
2 answers
import itertools
[''.join(value) for key, value in itertools.groupby(my_str)]
+6
source
>>> 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']
+2
source

Source: https://habr.com/ru/post/1612122/


All Articles