Home > front end >  How to group all the first characters of a string in a list of string , all second character of a st
How to group all the first characters of a string in a list of string , all second character of a st

Time:09-26

a=["cypatlyrm","aolsemone","nueeleuap"]

o/p needed is : canyoupleasetellmeyournamep

I have tried

for i in range(len(a)):
    for j in range(len(a)):
        res =a[j][i]

it gives o/p : canyouple

how to get full output ?

CodePudding user response:

You can use itertools.zip_longest with fill value as empty string'' and itertools.chain and the join the result to get what you want.

from itertools import zip_longest, chain

seq = ["cypatlyrm", "aolsemone", "nueeleuap"]

res = ''.join(chain.from_iterable(zip_longest(*seq, fillvalue='')))
print(res)

Output

canyoupleasetellmeyournamep

Using zip_longest makes sure that this also works with cases where the element sizes are not equal. If all elements in the list are guaranteed to be the same length then a normal zip would also work.

If all the elements have the same length then you can use this approach that does not need libraries that have to be imported.

seq = ["cypatlyrm", "aolsemone", "nueeleuap"]
res = ''

for i in range(len(seq[0])):
    for j in seq:
        res  = j[i]

print(res)
  • Related