What you want is the itertools
grouper()
recipe, which takes any arbitrary iterable and gives you groups of n
items from that iterable:
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 zip_longest(*args, fillvalue=fillvalue)
(Note that in 2.x, this is slightly different as zip_longest()
is called izip_longest()
!)
E.g:
>>> list(grouper("12345678", 2))
[('1', '2'), ('3', '4'), ('5', '6'), ('7', '8')]
You can then rejoin the strings with a simple list comprehension:
>>> ["".join(group) for group in grouper("12345678", 2)]
['12', '34', '56', '78']
If you might have less than a complete set of values, just use fillvalue=""
:
>>> ["".join(group) for group in grouper("123456789", 2, fillvalue="")]
['12', '34', '56', '78', '9']