interleave string

alex23 wuwei23 at gmail.com
Tue Feb 15 22:39:30 EST 2011


Andrea Crotti <andrea.crott... at gmail.com> wrote:
> At the moment I have this ugly inliner
>         interleaved = ':'.join(orig[x:x+2] for x in range(0, len(orig), 2))

I actually prefer this over every other solution to date. If you feel
its too much behaviour in one line, I sometimes break it out into
separate values to provide some in-code documentation:

>>> s = "xxaabbddee"
>>> get_two_chars_at = lambda i: s[i:i+2]
>>> string_index  = xrange(0, len(s), 2)
>>> ':'.join(get_two_chars_at(i) for i in string_index)
'xx:aa:bb:dd:ee'



More information about the Python-list mailing list