Reputation: 1479
I want to remove character from string seq_in = 'KPKPAJDSKGRPRRKAPPP'
at specific indices in the list ind = [0, 1, 2, 3, 8, 10, 11, 12, 13, 14, 16, 17, 18]
. The result should be 'AJDSGA'
. I tried remove()
the string by looping the ind
list, but each character's index was shifted.
How to remove many characters at index from the list without loop?
Upvotes: 0
Views: 51
Reputation: 117886
You can use a generator expression within join
using enumerate
to get the index of each letter. If the index isn't in ind
then keep it.
>>> ''.join(j for i,j in enumerate(seq_in) if i not in ind)
'AJDSGA'
As mentioned in the comments, your lookups will be faster if ind
is a set
than if it stays a list
>>> ind = {0, 1, 2, 3, 8, 10, 11, 12, 13, 14, 16, 17, 18}
>>> ''.join(j for i,j in enumerate(seq_in) if i not in ind)
'AJDSGA'
Upvotes: 3