how to split a string (or sequence) into pairs of characters?

Mark McEahern marklists at
Thu Aug 15 20:38:09 CEST 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


['aab', 'bcc', 'dde', 'e']


// m


More information about the Python-list mailing list