how to split a string (or sequence) into pairs of characters?
Mark McEahern
marklists at mceahern.com
Thu Aug 15 14:38:09 EDT 2002
> Can anyone come up with a better way of performing these operations? Extra
> kudos if it easily extends to any sublength and not just pairs.
better? yeah, i'll imagine i know what that means while i suggest that you
try this:
from __future__ import generators
def chunk(seq, size):
for i in range(0, len(seq), size):
yield seq[i:i+size]
s = "aabbccddee"
size = 3
pairs = [x for x in chunk(s, size)]
print pairs
Output:
['aab', 'bcc', 'dde', 'e']
cheers,
// m
-
More information about the Python-list
mailing list