views:

940

answers:

4

I'd like to create a slice object from a string; right now the only way seems through a cumbersome hacky eval statement

class getslice:
    def __getitem__(self, idx): return idx[0]
eval("getslice()[%s, 1]" %(":-1"))

thanks in advance.

Edit: Sorry if the original prompt was not clear, the input in this case was ":-1". The point was to parse the string. Ignacio Vazquez-Abrams's response at least solved the problem (and seems to work with reverse indexing as well), but I think my solution above is still more clear if not conceptually clean (and will work correctly if Python ever changes slicing syntax).

+1  A: 

use operator module:

in Python 2.5 or earlier: operator.getslice(obj,start,end)

in Python 2.6 or later: operator.getitem(obj,[start:end])

vartec
+1  A: 

If you want a slice object, why don't you just instantiate one?

s = slice(start, stop, step)

What are you meaning by "creating it from a string"?

unbeknown
A: 

A slice object is usually created using subscript notation, this notation uses slice() internally, as stated on the slice() documentation. What you want to do is:

your_string[start:end]

From the python tutorial:

Strings can be subscripted (indexed); like in C, the first character of a string has subscript (index) 0. There is no separate character type; a character is simply a string of size one. Like in Icon, substrings can be specified with the slice notation: two indices separated by a colon.

>>> word = 'Help' + 'A' 
>>> word[4]
'A'
>>> word[0:2]
'He'
>>> word[2:4]
'lp'

Slice indices have useful defaults; an omitted first index defaults to zero, an omitted second index defaults to the size of the string being sliced.

>>> word[:2]    # The first two characters
'He'
>>> word[2:]    # Everything except the first two characters
'lpA'
mpeterson
sorry, that's not what I was asking, I want to parse the slice, e.g. "-3::2" from a string, and return a slice object [see original question].
gatoatigrado
It's not clear from your question that that's what you were asking. I'm sorry I can't help you anymore, what I recommend you though is to read the Zen of Python and reconsider if what you are trying to do doesn't go against it, if it does it's probably a bad idea.
mpeterson
sure, I think most of my code meets that (thanks for the ref). I'm sorry I don't know how to clarify more; did you read the revised question (and comments below)?regards,Nicholas
gatoatigrado
"It's not clear from your question that that's what you were asking." - could you explain more? What's not clear, and how can I improve it?
gatoatigrado
+1  A: 
slice(*[{True: lambda n: None, False: int}[x == ''](x) for x in (mystring.split(':') + ['', '', ''])[:3]])
Ignacio Vazquez-Abrams
this is kinda wrong, e. g. '1:1:1:1' is not a correct slice string and '1 : 1 : 1 ' is.Should more something like this: slice(*map(lambda x: int(x.strip()) if x.strip() else None, mystring.split(':')))
pprzemek