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?
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'
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.