8

I want to split a string like:

'aaabbccccabbb'

into

['aaa', 'bb', 'cccc', 'a', 'bbb']

What's an elegant way to do this in Python? If it makes it easier, it can be assumed that the string will only contain a's, b's and c's.

3
  • possible duplicate of How to split this string with python? Commented Mar 1, 2012 at 12:35
  • 1
    No one suggested regular expressions? I am both impressed and saddened. Commented Mar 2, 2012 at 7:18
  • Yeah, it's a duplicate of the question Ethan linked to. But that question doesn't have a helpful title, IMO. Commented Mar 2, 2012 at 19:55

4 Answers 4

26

That is the use case for itertools.groupby :)

>>> from itertools import groupby
>>> s = 'aaabbccccabbb'
>>> [''.join(y) for _,y in groupby(s)]
['aaa', 'bb', 'cccc', 'a', 'bbb']
Sign up to request clarification or add additional context in comments.

1 Comment

I knew there'd be an easy way to do this!
3

You can create an iterator - without trying to be smart just to keep it short and unreadable:

def yield_same(string):
    it_str = iter(string)
    result = it_str.next()
    for next_chr in it_str:
        if next_chr != result[0]:
            yield result
            result = ""
        result += next_chr
    yield result


.. 
>>> list(yield_same("aaaaaabcbcdcdccccccdddddd"))
['aaaaaa', 'b', 'c', 'b', 'c', 'd', 'c', 'd', 'cccccc', 'dddddd']
>>> 

edit ok, so there is itertools.groupby, which probably does something like this.

Comments

2

Here's the best way I could find using regex:

print [a for a,b in re.findall(r"((\w)\2*)", s)]

Comments

1
>>> import re
>>> s = 'aaabbccccabbb'
>>> [m.group() for m in re.finditer(r'(\w)(\1*)',s)]
['aaa', 'bb', 'cccc', 'a', 'bbb']

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.