3

I have a string in Python that I want to separate into a list without any separators. The string is similar to a byte array: '0100100010011'

I want to separate the 1's and 0's from each other without using string.split() because that function requires a separator.

This should be my expected output: ['0', '1', '00', '1', '000', '1', '00', '11']

1

2 Answers 2

5

itertools.groupby is a quick way to do this. Without a key argument it will group by the value of the items in an iterable (like a string). Then you can just join the groups:

from itertools import groupby

s = '0100100010011'
[''.join(g) for k, g in groupby(s)]
# ['0', '1', '00', '1', '000', '1', '00', '11']

One small advantage of itertools when dealing with a lot of data is that it allows you to iterate over a large set of things with needing to save the entire set to memory. So for example, you could process these one at a time without allocating the entire list:

for k, g in groupby(s):
    group = ''.join(g) 
    # deal with a single group and forget it
Sign up to request clarification or add additional context in comments.

1 Comment

Short and sweet!
3

Regular expressions are an even easier way to do this.

Python 3.8.5 (default, May 27 2021, 13:30:53) 
[GCC 9.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> x = '0010110111000111'
>>> import re
>>> ex = r"(0+|1+)"
>>> z = re.findall(ex,x)
>>> z
['00', '1', '0', '11', '0', '111', '000', '111']
>>> 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.