Creating slice notation from string

Falcolas garrickp at
Thu Sep 3 16:45:25 CEST 2009

On Sep 2, 3:55 pm, bvdp <b... at> wrote:
> I'm trying to NOT create a parser to do this .... and I'm sure that
> it's easy if I could only see the light!
> Is it possible to take an arbitrary string in the form "1:2", "1",
> ":-1", etc. and feed it to slice() and then apply the result to an
> existing list?
> For example, I have a normal python list. Let's say that x = [1,2,3,4]
> and I have a string, call it "s', in the format "[2:3]". All I need to
> do is to apply "s" to "x" just like python would do.
> I can, of course, convert "x" to a list with split(), convert the 2
> and 3 to ints, and then do something like: x[a:b] ... but I'd like
> something more general. I think the answer is in slice() but I'm lost.
> Thanks.

You might also consider looking at the operator module, which provides
to potentially useful methods - itemgetter and getslice. Neither will
directly use the string containing the bare slice notation, however
they do provide another alternative to directly using eval.


More information about the Python-list mailing list