omkar joshi omkar joshi - 11 months ago 53
Python Question

python: join list elements into strings of 8

I have a python list of chars and want to join them to create a list of strings of 8 elements each
eg: x = ['0','0','1','a','4','b','6','2','2','1','4','1','5','7','9','8']
result = ['001a4b62', '21415798']

Answer Source

The itertools documentation contains a grouper recipe that groups consecutive items to fixed-sized groups:

from itertools import *

def grouper(iterable, n, fillvalue=None):
    "Collect data into fixed-length chunks or blocks"
    # grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx
    args = [iter(iterable)] * n
    return izip_longest(fillvalue=fillvalue, *args)

Now you can just group into lists of size 8, and turn each one to a string:

>>> [''.join(e) for e in grouper(x, 8)]
['001a4b62', '21415798']