Creating slice notation from string
Robert Kern
robert.kern at gmail.com
Wed Sep 2 18:11:02 EDT 2009
On 2009-09-02 16:55 PM, bvdp 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.
For a one-liner:
x[slice(*map(int, x[1:-1].split(':')))]
--
Robert Kern
"I have come to believe that the whole world is an enigma, a harmless enigma
that is made terrible by our own mad attempt to interpret it as though it had
an underlying truth."
-- Umberto Eco
More information about the Python-list
mailing list