Skip to content
Advertisement

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

Is there a pythonic way to insert an element into every 2nd element in a string?

I have a string: ‘aabbccdd’ and I want the end result to be ‘aa-bb-cc-dd’.

I am not sure how I would go about doing that.

Advertisement

Answer

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

JavaScript

The t can also be eliminated with

JavaScript

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.

JavaScript

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

JavaScript

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

JavaScript

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

JavaScript

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

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement