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?
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?
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/
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
>>> 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')