Here is my list:
liPos = [(2,5),(8,9),(18,22)]
The first item of each tuple is the starting position and the second is the ending position. Then I have a string like this:
s = "I hope that I will find an answer to my question!"
Now, considering my liPos
list, I want to format the string by removing the chars between each starting and ending position (and including the surrounding numbers) provided in the tuples. Here is the result that I want:
"I tt I will an answer to my question!"
So basically, I want to remove the chars between 2 and 5 (including 2 and 5), then between 8,9 (including 8 and 9) and finally between 18,22 (including 18 and 22).
Any suggestion?
This assumes that liPos
is already sorted, if it is not used sorted(liPos, reverse=True)
in the for
loop.
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
Here is an alternative method that constructs a new list of slice tuples to include, and then joining the string with only those included portions.
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))
To make this slightly easier to understand, here are the slices generated by izip_longest
:
>>> list(izip_longest(*[iter(chain([0], *liPos))]*2))
[(0, 2), (6, 8), (10, 18), (23, None)]
liPos = [(2,5),(8,9),(18,22)]
s = "I hope that I will find an answer to my question!"
exclusions = set().union(* (set(range(t[0], t[1]+1)) for t in liPos) )
pruned = ''.join(c for i,c in enumerate(s) if i not in exclusions)
print pruned
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With