Is it possible to get index values (start,end) of a slice? For example
In [1]: s = "Test string"
In [2]: s[-6:] # get slice indexes (5,11)
Out[2]: 'string'
In [3]: s = "Another test string"
In [4]: s[8:] # get slice indexes (8,19)
Out[4]: 'test string'
In other words, I don't need the substring itself but only the indexes as a tuple (start,end).
You can use python's slice
object like so:
In [23]: s = "Test string"
In [24]: slice(-6, None).indices(len(s))
Out[24]: (5, 11, 1)
In [25]: s = "Another test string"
In [26]: slice(8, None).indices(len(s))
Out[26]: (8, 19, 1)
EDIT: using Eric's improvement to use None instead of len(s) for the stop argument
class SliceGetter(object):
def __init__(self, inner):
self.size = len(inner)
def __getitem__(self, index):
return index.indices(self.size)[:2]
>>> SliceGetter("Test string")[-6:]
(5, 11)
>>> SliceGetter("Another test string")[8:]
(8, 19)
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