Creating slice notation from string

Jan Kaliszewski zuo at chopin.edu.pl
Thu Sep 3 00:33:29 CEST 2009


03-09-2009 o 00:11:17 MRAB <python at mrabarnett.plus.com> wrote:

> 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.
>>
>  >>> x = [1,2,3,4]
>  >>> s = "[2:3]"
>  >>> # Using map.
>  >>> x[slice(*map(int, s.strip("[]").split(":")))]
> [3]
>  >>> # Using a list comprehension.
>  >>> x[slice(*[int(i) for i in s.strip("[]").split(":")])]
> [3]

Of course, you could also do something like this:

     eval('x' + s)
or
     eval(str(x) + s)

-- but it's worse: less secure (e.g. if s could be user-typed) and most
probably much more time-consuming (especially the latter).

Cheers,
*j

-- 
Jan Kaliszewski (zuo) <zuo at chopin.edu.pl>



More information about the Python-list mailing list