Creating slice notation from string

Robert Kern robert.kern at gmail.com
Wed Sep 2 19:35:53 EDT 2009


On 2009-09-02 17:55 PM, Bob van der Poel wrote:
>
>> For a one-liner:
>>
>>     x[slice(*map(int, x[1:-1].split(':')))]
>
> Thanks.
>
> Almost works :)
>
> For s="[2]" 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?

Expanding out to a couple of lines now:

slice_args = []
for i in s.strip("[]").split(':'):
     if i.strip() == '':
         slice_args.append(None)
     else:
         slice_args.append(int(i))

y = x[slice(*slice_args)]


-- 
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