interleave string

A

Andrea Crotti

Just a curiosity not a real problem, I want to pass from a string like

xxaabbddee
to
xx:aa:bb:dd:ee

so every two characters insert a ":".
At the moment I have this ugly inliner
interleaved = ':'.join(orig[x:x+2] for x in range(0, len(orig), 2))

but also something like this would work
[''.join((x,y)) for x, y in zip(orig[0::2], orig[1::2])]

any other ideas?
 
W

Wojciech Mu³a

Just a curiosity not a real problem, I want to pass from a string like

xxaabbddee
to
xx:aa:bb:dd:ee

so every two characters insert a ":".
At the moment I have this ugly inliner
interleaved = ':'.join(orig[x:x+2] for x in range(0,
len(orig), 2))

but also something like this would work
[''.join((x,y)) for x, y in zip(orig[0::2], orig[1::2])]

any other ideas?

import re

s = 'xxaabbddee'
m = re.compile("(..)")
s1 = m.sub("\\1:", s)[:-1]

w.
 
A

Alex Willmer

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.
 
A

alex23

Andrea Crotti said:
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'
 
S

Steven D'Aprano

Andrea Crotti said:
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.

Agreed. To me, it's the simplest, least contrived way to solve the
problem.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,754
Messages
2,569,527
Members
44,998
Latest member
MarissaEub

Latest Threads

Top