-4

Let's they I have the list ['abc', 'def', 'gh'] I need to get a string with the contents of the first char of the first string, the first of the second and so on.

So the result would look like this: "adgbehcf" But the problem is that the last string in the array could have two or one char.

I already tried to nested for loop but that didn't work.

Code:

n = 3 # The encryption number    

for i in range(n):
    x = [s[i] for s in partiallyEncrypted]
    fullyEncrypted.append(x)
Dimitris Fasarakis Hilliard
  • 150,925
  • 31
  • 268
  • 253
Baron TV
  • 11
  • 4

4 Answers4

2

a version using itertools.zip_longest:

from itertools import zip_longest

lst = ['abc', 'def', 'gh']
strg = ''.join(''.join(item) for item in zip_longest(*lst, fillvalue=''))
print(strg)

to get an idea why this works it may help having a look at

for tpl in zip_longest(*lst, fillvalue=''):
    print(tpl)
hiro protagonist
  • 44,693
  • 14
  • 86
  • 111
0

I guess you can use:

from itertools import izip_longest
l = ['abc', 'def', 'gh']
print "".join(filter(None, [i for sub in izip_longest(*l) for i in sub]))
# adgbehcf
Pedro Lobito
  • 94,083
  • 31
  • 258
  • 268
0

Please don't use this:

''.join(''.join(y) for y in zip(*x)) + 
''.join(y[-1] for y in x if len(y) == max(len(j) for j in x))
blacksite
  • 12,086
  • 10
  • 64
  • 109
0

Having:

l = ['abc', 'def', 'gh']

This would work:

s = ''

In [18]: for j in range(0, len(max(l, key=len))):
    ...:     for elem in l:
    ...:         if len(elem) > j:
    ...:             s += elem[j]

In [28]: s
Out[28]: 'adgbehcf'
elena
  • 3,740
  • 5
  • 27
  • 38