在python字符串/数组中的多个指定位置插入值

2024-09-29 01:23:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我想在python字符串/数组中插入多个指定位置的值。你知道吗

例如我的输入字符串: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? 我希望这有意义!你知道吗

非常感谢, 卷曲的。你知道吗


Tags: to字符串posconvertstring数组seqlist
3条回答

按相反顺序插入即可:

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

这样做可以:

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'

相关问题 更多 >