'Group a string into 3s in a loop (python)

I have a nine character string and need to perform operations on groups of three characters in a loop.

How would i achieve this in python?



Solution 1:[1]

Maybe something like this?

>>> a = "123456789"
>>> for grp in [a[:3], a[3:6], a[6:]]:
    print grp

Of course, if you need to generalize,

>>> def split3(aString):
        while len(aString) > 0:
                yield aString[:3]
                aString = aString[3:]


>>> for c in split3(a):
        print c

Solution 2:[2]

>>> s = "123456789"
>>> import textwrap
>>> textwrap.wrap(s,3)
['123', '456', '789']

or you can use itertools

import itertools
def grouper(n, iterable):
    args = [iter(iterable)] * n
    return itertools.izip_longest(*args)

for i in grouper(3,"o my gosh"):
    print i

output

$ ./python.py
('o', ' ', 'm')
('y', ' ', 'g')
('o', 's', 'h')

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Miron Brezuleanu
Solution 2