Earlier today I needed to iterate over a string 2 characters at a time for parsing a string formatted like \"+c-R+D-E\"
(there are a few extra letters).
from itertools import izip_longest
def grouper(iterable, n, fillvalue=None):
args = [iter(iterable)] * n
return izip_longest(*args, fillvalue=fillvalue)
def main():
s = "+c-R+D-e"
for item in grouper(s, 2):
print ' '.join(item)
if __name__ == "__main__":
main()
##output
##+ c
##- R
##+ D
##- e
izip_longest
requires Python 2.6( or higher). If on Python 2.4 or 2.5, use the definition for izip_longest
from the document or change the grouper function to:
from itertools import izip, chain, repeat
def grouper(iterable, n, padvalue=None):
return izip(*[chain(iterable, repeat(padvalue, n-1))]*n)