How to split a string by character sets that are different in python


I want to split an string I have by characters that are different that the others into a list. for example, if I have string ccaaawq, I want my program to give me ['cc', 'aaa', 'w', 'q']. Since there is no single differentiator between each split, I’m wondering what is the best approach to solving this problem.
thanks in advance for your answers


You can use itertools.groupby:

from itertools import groupby

s = "ccaaawq"

out = ["".join(g) for _, g in groupby(s)]


['cc', 'aaa', 'w', 'q']

Answered By – Andrej Kesely

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published