O.rka
O.rka

Reputation: 30687

Extracting string based on 2 lists of integers. Python

seq = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'

start = [2,9,18]
end = [6,12,20]

#output = seq[end[k]:start[k+1]]

i'm trying to the sequence between end[k] and start[k+1] #seq[end[k]:start[k+1]]

so there should be 2 sequences in this case.

outp1 = seq[6:9] #'GHI'

out2 = seq[12:18] #'MNOPQR'

Upvotes: 3

Views: 59

Answers (2)

Kousik
Kousik

Reputation: 22425

for i in range(len(end)-1):
    seq[end[i]:start[i+1]]

answer:-
    'GHI'
    'MNOPQR'

Upvotes: 3

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 250961

Use zip:

>>> seq = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
>>> start = [2,9,18]
>>> end = [6,12,20]
>>> for x,y in zip(end, start[1:]):
...     print seq[x:y]
...     
GHI
MNOPQR

Memory efficient version:

>>> from itertools import izip,islice
>>> for x,y in izip(end,islice(start,1,None)):
    print seq[x:y]
...     
GHI
MNOPQR

Upvotes: 5

Related Questions