Is there some concise way to split up a string of 0s and 1s into the homogeneous, contiguous segments of all 0s and all 1s? Example in the title.
I can of course do it with a nested loop, conditionals, and the .count()
method, but this seems like something there'd be a library function for. I'm just not sure how to search for it if there is.
Yes you can using itertools.groupby
from itertools import groupby
a = "000111010010111"
result = ["".join(list(group)) for key, group in groupby(a)]
What happened? We used itertools.groupby
to group consecutive terms. A new group is created every time the key element changes (which is when a 0 turns into a 1 or a 1 turns into a 0 in your example). The inner lists are then joined to arrive at your desired output.
Output:
['000', '111', '0', '1', '00', '1', '0', '111']
This will work for any string (not just 1s and 0s) and will group items together based on their consecutive appearances.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With