Creating slice notation from string
Bob van der Poel
bob at mellowood.ca
Thu Sep 3 01:56:36 CEST 2009
On Sep 2, 4:43 pm, "Jan Kaliszewski" <z... at chopin.edu.pl> wrote:
> 03-09-2009 o 00:55:10 Bob van der Poel <b... at mellowood.ca> wrote:
> >> For a one-liner:
> >> x[slice(*map(int, x[1:-1].split(':')))]
> > Thanks.
> > Almost works :)
> > For s="" and s="[1:2]" it's fine. But, if I have
> > s = "[:2]" then I get:
> >>>> x[slice(*[int(i) for i in s.strip("").split(":")])]
> > Traceback (most recent call last):
> > File "<stdin>", line 1, in <module>
> > ValueError: invalid literal for int() with base 10: ''
> > Similar problem with [2:].
> > Ideas?
> x = [1,4,3,5,4,6,5,7]
> s = '[3:6]'
> x[slice(*((int(i) if i else None)
> for i in s.strip("").split(":")))]
Thanks. I think this will work fine. If I paste the above in a python
shell it's perfect. And if I paste it into my code it errors out ...
so I have to look a bit more. Always the problem with one-liners if
figuring out where the error is. I think it's just a naming thing ...
I'm sure I'll get it soon. I'll shout if I find more problems.
More information about the Python-list