Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - get slice index

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).

like image 898
armandino Avatar asked Nov 11 '12 20:11

armandino


2 Answers

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

like image 194
davidbrai Avatar answered Oct 17 '22 21:10

davidbrai


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)
like image 20
Eric Avatar answered Oct 17 '22 23:10

Eric