Skip to main content
 首页 » 编程设计

python之字符串多索引替换而不影响插入顺序

2025年05月04日42yxwkf

假设我有一个字符串值 str=xxx。现在我想通过多索引替换它,例如 {(1, 3):'rep1', (4, 7):'rep2', (8, 9):'rep3'},不打乱索引顺序。我该怎么做?

伪代码(在 Python 2.7 中):

str = 'abcdefghij' 
replacement = {(1, 3):'123', (4, 7):'+', (8, 9):'&'} # right index isn't include 
 
# after some replacements: 
str = some_replace(str, replacement) 
# i want to get this: 
print str 
# 'a123d+h&j' 

请您参考如下方法:

# since string is immutable, make a list out of the string to modify in-place 
lst = list(str) 

使用slice修改items,关于slice和assignment的更详细的解释可以看here ; slice(*k) 根据替换键创建一个 slice 对象。例如,slice(*(1, 3)) 给出了 slice(1, 3) 的切片,它等同于 lst[1:3] 当用作索引时,调用切片上的赋值时将相应的元素替换为相应的值:

# Here sort the index in reverse order so as to avoid tracking the index change due to the  
# difference of the sizes between the index and replacement 
for k, v in sorted(replacement.items(), reverse=True): 
    lst[slice(*k)] = v 
 
''.join(lst) 
# 'a123d+h&j'