user975135
user975135

Reputation:

create new string by adding characters of smaller strings one after another

You have strings "aaaaa" "bbbbb" "ccccc" "ddddd"

Now you want to generate the string:

"abcdabcdabcdabcdabcd"

How would be the fastest way to do it?

PS. This is a very simplified example. I really need to generate the new string from the existing smaller strings.

Upvotes: 1

Views: 325

Answers (3)

Spencer Rathbun
Spencer Rathbun

Reputation: 14900

Use izip_longest from the itertools library, and the flatten recipe from the same library.

from itertools import izip_longest, chain
def flatten(listOfLists):
    "Flatten one level of nesting"
    return chain.from_iterable(listOfLists)

result = ''.join(flatten(izip_longest("aaaaa", "bbbbb", "ccc", "dddd", fillvalue='')))

Upvotes: 1

jonathan.hepp
jonathan.hepp

Reputation: 1643

string1 = "aaaaaaaaa"
string2 = "bbbbbbbbb"
string3 = "ccccccccc"
string4 = "ddddddddd"
new_string = ""
for i in range(0,len(string1)):
    new_string = new_string+string1[i]+string2[i]+string3[i]+string4[i]
print (new_string)

Results:

abcdabcdabcdabcdabcdabcdabcdabcdabcd

Upvotes: 0

Mark Byers
Mark Byers

Reputation: 838106

If the strings are of equal length you can use zip:

result = ''.join(map(''.join, zip(*strings)))

Upvotes: 3

Related Questions