armandino
armandino

Reputation: 18538

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

Upvotes: 6

Views: 5404

Answers (3)

davidbrai
davidbrai

Reputation: 1229

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

Upvotes: 16

Eric
Eric

Reputation: 97601

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)

Upvotes: 3

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 250971

define your own function :

In [119]: def start_end(strs,x):
    if x>0:
        return x,len(strs)  
    else:
        return len(strs)+x,len(strs)
   .....:     

In [120]: start_end("Test String",-6)
Out[120]: (5, 11)

In [122]: func("Another test string",8)
Out[122]: (8, 19)

Upvotes: 0

Related Questions