Random
Random

Reputation: 4769

Zipping strings according to the longer string

Given 2 strings:

a='AAAAAAAA'
b='GGGG'

I'd like to have a result of

'AG','AG','AG','AG','A','A','A','A'

So far I've tried 2 ways and both of them are returning only 4 items

Map approach:

list(map(lambda x,y:x+y,a,b))

result:

'AG','AG','AG','AG'

Zip approach:

list(zip(a,b))

result:

('A','G'),('A','G'),('A','G'),('A','G')

Map method looks closer to what I'm looking for

Upvotes: 2

Views: 139

Answers (3)

Karishnu Poddar
Karishnu Poddar

Reputation: 313

a='AAAAAAA'
b='GGGG'
listab=[] #declaring new list
for i in range(0,len(a)): #loops for length of a
    item = a[i:i+1] + b[i:i+1] #concatenates a letter from a and b
    listab.append(item) 
print (listab)
  1. Program declares two variables a and b.
  2. Declares an empty list
  3. Starts a for loop assuming variable (a) is longer (you can always write an if statement to check which one is longer if need be)
  4. for i in range(0,len(a)) increases integer i from 0 to the length of (a)
  5. Then add the letters at the same position in (a) and (b) and append to the empty list you created.

string[start position: end position] returns the part of the string between the start and the end-1 position.

Upvotes: 0

John La Rooy
John La Rooy

Reputation: 304205

No imports is a strange request, however:

>>> a='AAAAAAAA'
>>> b='GGGG'
>>> [a[i: i + 1] + b[i: i + 1] for i in range(max(map(len, (a, b))))]
['AG', 'AG', 'AG', 'AG', 'A', 'A', 'A', 'A']

or

>>> [''.join(i) for i in zip(a, b)] + list(a[len(b):]) + list(b[len(a):])
['AG', 'AG', 'AG', 'AG', 'A', 'A', 'A', 'A']

importing itertools is a far better solution

Upvotes: 2

Kasravnd
Kasravnd

Reputation: 107297

You can use itertools.zip_longest which accepts a fillvalue argument :

>>> from itertools import zip_longest
>>> a='AAAAAAAA'
>>> b='GGGG'

>>> [''.join(i) for i in zip_longest(a,b,fillvalue='')]
['AG', 'AG', 'AG', 'AG', 'A', 'A', 'A', 'A']

If you want to do this without importing a library you can have a look at zip_longest source code.And you might note that this is the most pythonic way to do such task.

By the way you can use another approaches which are not pythonic and efficient, for example you can use atr.ljust to fill the b with a special character and makes its size equal to a then zip them and use a list comprehension to get the expected output :

>>> [''.join((i,j)) if j != '.' else i for i,j in zip(a,b.ljust(len(a),'.'))]
['AG', 'AG', 'AG', 'AG', 'A', 'A', 'A', 'A']

Upvotes: 6

Related Questions