Предполагается, что liPos
уже отсортировано, если оно не используется sorted(liPos, reverse=True)
в цикле for
.
liPos = [(2,5),(8,9),(18,22)]
s = "I hope that I will find an answer to my question!"
for begin, end in reversed(liPos):
s = s[:begin] + s[end+1:]
print s
Вот альтернативный метод, который создает новый список кортежей срезов для включения, а затем объединяет строку только с теми включенными частями.
from itertools import chain, izip_longest
# second slice index needs to be increased by one, do that when creating liPos
liPos = [(a, b+1) for a, b in liPos]
result = "".join(s[b:e] for b, e in izip_longest(*[iter(chain([0], *liPos))]*2))
Чтобы это было немного легче понять, вот кусочки, сгенерированные izip_longest
:
>>> list(izip_longest(*[iter(chain([0], *liPos))]*2))
[(0, 2), (6, 8), (10, 18), (23, None)]