interleave string

Alex Willmer alex at
Tue Feb 15 08:21:12 EST 2011

On Feb 15, 10:09 am, Wojciech Muła
<wojciech_m... at> wrote:
> import re
> s = 'xxaabbddee'
> m = re.compile("(..)")
> s1 = m.sub("\\1:", s)[:-1]

One can modify this slightly:

s = 'xxaabbddee'
m = re.compile('..')
s1 = ':'.join(m.findall(s))

Depending on one's taste this could be clearer. The more general
answer, from the itertools docs:

from itertools import izip_longest

def grouper(n, iterable, fillvalue=None):
    "grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx"
    args = [iter(iterable)] * n
    return izip_longest(fillvalue=fillvalue, *args)

s2 = ':'.join(''.join(pair) for pair in grouper(2, s, ''))

Note that this behaves differently to the previous solutions, for
sequences with an odd length.

More information about the Python-list mailing list