Iterate over a string 2 (or n) characters at a time in Python

I don’t know about cleaner, but there’s another alternative:

for (op, code) in zip(s[0::2], s[1::2]):
    print op, code

A no-copy version:

from itertools import izip, islice
for (op, code) in izip(islice(s, 0, None, 2), islice(s, 1, None, 2)):
    print op, code

Leave a Comment