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.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Assume the string’s length is always an even number,
The
tcan also be eliminated withThe 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.
Then the
zipfunction is used to combine them into an iterable of tuples.But tuples aren’t what we want. This should be a list of strings. This is the purpose of the list comprehension
Finally we use
str.join()to combine the list.The first piece of code is the same idea, but consumes less memory if the string is long.