1

I have a sequence like this:

ABCDEFGHIJKL

I would like to insert the strings:

'-(c0)-' after elements 1 and 3
'-(c1)-' after elements 2 and 4
'-(c2)-' after elements 5 and 6

This is the kind of code I was writing:

list_seq = list('ABCDEFGHIJKL')
new_list_seq = list('ABCDEFGHIJKL')
start_end = [(1,3), (2,4), (5,6)]
for index,i in enumerate(start_end):
    pair_name = '-(c' + str(index) + ')-'
    start_index = int(i[0])  
    end_index = int(i[1]) 
    new_list_seq.insert(start_index, pair_name)
    new_list_seq.insert(end_index, pair_name)
print ''.join(new_list_seq)

The output I would want is:

AB-(c0)-C-(c1)-D-(c0)-E-(c1)-F-(c2)-G-(c2)-HIJKL

(where c0 was inserted after 1 and 3 positions, c1 was inserted after 2 and 4, and c2 was inserted after 5 and 6).

But the output I get is:

A-(c0)--(c1)-B-(c1)--(c2)--(c2)--(c0)-CDEFGHIJKL

I think possibly the problem is that as I incorporate an item into the string, the indices change, so then all subsequent inclusions after the first one are not in the right positions?

Could anyone explain how to do this properly?

1
  • 1
    You could also just insert your elements the other way round from last to first. then you would not change the target index of the next item to be inserted. Commented Aug 22, 2018 at 12:12

2 Answers 2

1

Based on @r.user.05apr's very good idea to simply step through the whole input string char by char, I'd like to add a possibility to generalize this for an arbitrary long start_end-list:

s = 'ABCDEFGHIJKL'
res = list()
for nr, sub in enumerate(s):
    res.append(sub)
    try:
        i = [nr in x for x in start_end].index(True)
        res.append('-(c' + str(i) + ')-')
    except:
        pass
res = ''.join(res)        
print(res)    
# AB-(c0)-C-(c1)-D-(c0)-E-(c1)-F-(c2)-G-(c2)-HIJK
Sign up to request clarification or add additional context in comments.

Comments

1

Hope it helps:

s = 'ABCDEFGHIJKL'
res = list()
for nr, sub in enumerate(s):
    res.append(sub)
    if nr in (1, 3):
        res.append('-(c0)-')
    elif nr in (2, 4):
        res.append('-(c1)-')
    elif nr in (5, 6):
        res.append('-(c2)-')
res = ''.join(res)        
print(res)    
# AB-(c0)-C-(c1)-D-(c0)-E-(c1)-F-(c2)-G-(c2)-HIJKL 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.