tags:

views:

66

answers:

3

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?

+3  A: 

Simplest way:

>>> s = "123456789"
>>> for group in (s[:3], s[3:6], s[6:]): print group
...
123
456
789

In the more general case, look at: http://code.activestate.com/recipes/303799-chunks/

truppo
+3  A: 

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
Miron Brezuleanu
+1 Wouldn't `while aString` look better than `while len(aString) > 0`?
jellybean
Maybe :-) I prefer clearer booleans, but this is a matter of personal taste.
Miron Brezuleanu
+1  A: 
>>> 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')
ghostdog74
-1: This will not behave as expected for all strings: textwrap.wrap("i am sam!", 3) = ['i', 'am ', 'sam', '!']
truppo