gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 08:42:25 25 4
gpt4 key购买 nike

假设我有一个字符串值 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'

关于python - 字符串多索引替换而不影响插入顺序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43764457/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com