ActiveState Code

Recipe 496784: Split String into n-size pieces


The code below takes a string and returns a list containing the n-sized pieces of the string. For example: splitCount('aabbccdd', 2) => ['aa', 'bb', 'cc', 'dd']

Python
1
2
def splitCount(s, count):
     return [''.join(x) for x in zip(*[list(s[z::count]) for z in range(count)])]

Discussion

This is useful if you know that data is in a certain format. I use it to parse dates that are not delimited like: 060506 (often found in filenames, etc).

Anyways it seems like kind of a basic operation on strings.

It seems like there should be a more pythonic way to do this, but I can't think of one.

Comments

  1. 1. At 1:22 p.m. on 6 jun 2006, Ian Bicking said:

    For sequences... I think this might be better, and works for any sequences that support slicing and len() (thus including lists):

    def split_len(seq, length):
        return [seq[i:i+length] for i in range(0, len(seq), length)]
    

Sign in to comment