python字符串切片与列表

Sha*_*kan 4 python string list slice

这是我的清单:

liPos = [(2,5),(8,9),(18,22)]
Run Code Online (Sandbox Code Playgroud)

每个元组的第一项是起始位置,第二项是结束位置.然后我有一个像这样的字符串:

s = "I hope that I will find an answer to my question!"
Run Code Online (Sandbox Code Playgroud)

现在,考虑到我的liPos列表,我想通过删除元组中提供的每个起始位置和结束位置(以及包括周围数字)之间的字符来格式化字符串.这是我想要的结果:

"I tt I will an answer to my question!"
Run Code Online (Sandbox Code Playgroud)

基本上,我想删除2到5之间的字符(包括2和5),然后是8,9(包括8和9)之间的字符,最后是18,22之间(包括18和22之间).

有什么建议吗?

And*_*ark 5

假设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
Run Code Online (Sandbox Code Playgroud)

下面是一个替代方法,它构造一个新的切片元组列表,然后将字符串与仅包含的部分连接起来.

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))
Run Code Online (Sandbox Code Playgroud)

为了使这更容易理解,这里是由izip_longest以下生成的切片:

>>> list(izip_longest(*[iter(chain([0], *liPos))]*2))
[(0, 2), (6, 8), (10, 18), (23, None)]
Run Code Online (Sandbox Code Playgroud)