将多个指定位置的值插入 python string/array

Insert value at multiple specified positions into a python string/array

我想将多个指定位置的值插入 python string/array.

例如我的输入字符串:SARLSAMLVPVTPEVKPK

指定位置:1,5,12

期望的输出:S*ARLS*AMLVPVT*PEVKPK

我试过了:

seq="SARLSAMLVPVTPEVKPK" #string
pos=[1,5,12] #positions
arr=list(seq) #convert string to array
arr.insert(pos,"*") # NOT WORK!
arr.insert(pos[0],"*")
print(''.join(arr))

看来我一次只能插入一个位置,因此下一次插入的指定位置的索引必须更改。 有没有一种优雅的方法可以做到这一点,或者我是否必须遍历插入位置并为每个额外的插入位置添加 +1? 我希望这是有道理的!

非常感谢, 卷发。

像这样的事情会做:

seq="SARLSAMLVPVTPEVKPK" #string
pos=[1,5,12] #positions
arr=list(seq) #convert string to array
_ = map(lambda k: arr.insert(k, "*"), pos[::-1])
print(''.join(arr))

seq="SARLSAMLVPVTPEVKPK" #string
pos=[1,5,12] #positions
arr=list(seq) #convert string to array
for k in pos[::-1]:
    arr.insert(k, "*")
print(''.join(arr))

简单方法:

temp =  ""
temp += seq[:pos[0]]
temp += "*"
for i in range(1,len(pos)):
    temp += seq[pos[i-1]:pos[i]]
    temp += "*"
temp += seq[pos[-1]:]
print (temp)    # 'S*ARLS*AMLVPVT*PEVKPK'

只需按相反顺序插入即可:

seq="SARLSAMLVPVTPEVKPK" #string
pos=[1,5,12] #positions
arr = list(seq)
for idx in sorted(pos, reverse=True):
    arr.insert(idx,"*")
print ''.join(arr)