Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pythonic way to insert every 2 elements in a string

Tags:

python

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.

like image 805
root Avatar asked Jul 15 '10 18:07

root


People also ask

How do you put a character after every two characters in a string?

To insert a character after every N characters, call the replace() method on the string, passing it the following regular expression - str. replace(/. {2}/g, '$&c') . The replace method will replace every 2 characters with the characters plus the provided replacement.

How do you add two characters together in Python?

The + operator lets you combine two or more strings in Python. This operator is referred to as the Python string concatenation operator. The + operator should appear between the two strings you want to merge. This code concatenates, or merges, the Python strings “Hello ” and “World”.

How do you put periods in between letters in Python?

Alexander Davison. You can "add" (concatenate) the period character to the end of the string. For example: "Harpreet is learning Python" + "!" # This code returns "Harpreet is learning Python!"

How do you add characters after every character in Python?

Method #2 : Using zip() + join() In this, zip function converts the characters to iterable tuples, split function is used to separate odd and even characters. Then list comprehension is responsible to convert the tuples to list of strings and at last result is joined using the join function.


1 Answers

>>> s = 'aabbccdd' >>> '-'.join(s[i:i+2] for i in range(0, len(s), 2)) 'aa-bb-cc-dd' 
like image 93
SilentGhost Avatar answered Sep 17 '22 12:09

SilentGhost