Creating slice notation from string

Bob van der Poel bob at mellowood.ca
Thu Sep 3 02:32:09 CEST 2009


On Sep 2, 5:16 pm, Steven D'Aprano <st... at REMOVE-THIS-
cybersource.com.au> wrote:
> On Wed, 02 Sep 2009 16:41:34 -0700, Bob van der Poel wrote:
>
> > But, translating 1, 2 or 3 ints into a valid splice isn't quit that
> > easy? I could figure each value, and convert them to either int or None
> > (key is the None! From my previous try '' doesn't work!)
>
> > But, I still need three possible lines:
>
> >  if len(i) == 1:
> >     x=x[i(0)]
> >   else if len(i) == 2:
> >     x=x[i(0):i(1)]
> >    ....
>
> items = [int(n) for n in slice_string.split(":")]
> slice(*items)
>
> --
> Steven

Actually, nither this or Jan's latest is working properly. I don't
know if it's the slice() function or what (I'm using python 2.5). But:

x = [1,2,3,4,5]
slice_string="2"
items = [int(n) if n else None for n in slice_string.split(":")]
[slice(*items)]
[1, 2]

not the expected:

[3]

Things like -1 don't work either.

I'm really not sure what's going on, but I suspect it's the way that
slice() is getting filled when the slice string isn't a nice one with
each ":" present?




More information about the Python-list mailing list