How to insert a character after every 2 characters in a string

Solution 1:

>>> s = 'aabbccdd'
>>> '-'.join(s[i:i+2] for i in range(0, len(s), 2))
'aa-bb-cc-dd'

Solution 2:

Assume the string's length is always an even number,

>>> s = '12345678'
>>> t = iter(s)
>>> '-'.join(a+b for a,b in zip(t, t))
'12-34-56-78'

The t can also be eliminated with

>>> '-'.join(a+b for a,b in zip(s[::2], s[1::2]))
'12-34-56-78'

The algorithm is to group the string into pairs, then join them with the - character.

The code is written like this. Firstly, it is split into odd digits and even digits.

>>> s[::2], s[1::2]
('1357', '2468')

Then the zip function is used to combine them into an iterable of tuples.

>>> list( zip(s[::2], s[1::2]) )
[('1', '2'), ('3', '4'), ('5', '6'), ('7', '8')]

But tuples aren't what we want. This should be a list of strings. This is the purpose of the list comprehension

>>> [a+b for a,b in zip(s[::2], s[1::2])]
['12', '34', '56', '78']

Finally we use str.join() to combine the list.

>>> '-'.join(a+b for a,b in zip(s[::2], s[1::2]))
'12-34-56-78'

The first piece of code is the same idea, but consumes less memory if the string is long.