Slice objects. How to apply them to strings?

Dale Strickland-Clark dale at riverhall.NOTHANKS.co.uk
Wed Mar 27 19:12:57 EST 2002


I'm using Python 2.1 here but this still seems to apply on 2.2

I have a little string-based class which needs to emulate strings for
most things. This includes slicing.

So I need a __getitem__ magic method. 

This will get passed a slice object.

How am I supposed to translate this into a string slice? 

This seems to be the tidiest I can come up with and it's a mess:

def __getitem__(self, item):
    if item.step:
        return self.s[item.start: item.stop: item.step]
    if item.start:
        return self.s[item.start: item.stop]
    return self.s[item.stop]

If 'item' is a slice object, shouldn't I just be able to say:

    self.s[item]
?

Wouldn't this be really sensible?

What's worse, is that I can't even do this:

import operator
operator.getitem(self.s, item)

Somebody please tell me I'm being dim and I've missed something. How
do you apply a slice object to a sequence?

Thanks
--
Dale Strickland-Clark
Riverhall Systems Ltd



More information about the Python-list mailing list