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

时间:2017-05-03 15:36:01

标签: python

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

1 个答案:

答案 0 :(得分:5)

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

使用切片修改项目,可以找到关于切片和赋值的更强解释here; slice(*k)从替换的键创建切片对象。例如,slice(*(1, 3))给出一片slice(1, 3),当用作索引时等于lst[1:3],并在调用切片上的赋值时用相应的值替换相应的元素: / p>

# 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'