Creating slice notation from string

Ethan Furman ethan at stoneleaf.us
Thu Sep 3 05:28:40 CEST 2009


On Wed, 02 Sep 2009 17:36:36 -0700, Bob van der Poel <bob at mellowood.ca>  
wrote:

> On Sep 2, 4:27 pm, Ethan Furman <et... at stoneleaf.us> wrote:
>> 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?
>>
>> try:
>>      start, end = s[1:-1].split(':')
>> except ValueError:
>>      start = int(s[1:-1] # only one value specified
>>      end = start+1
>> start = int(start) if start else 0
>> end = int(end) if end else len(x)
>> x[start:end]
>>
>> ~Ethan~
>
> Yes ... I see. I'm thinking that eval() is looking very nice. If we do
> it the above way we also have to check for empties using things like
> [1::2] and I'm really getting confused about the possibilities :)

How about:

[untested]
s = s[1:-1]  # strip the brackets
if s.count(':') == 0:
     return x[int(s)]
while s.count(':') < 2:
     s += ':'
start, stop, step = s.split(':')
start = int(start) if start else 0
end = int(stop) if stop else len(x)
step = int(step) if step else 1
return x[start:stop:step)

~Ethan~



More information about the Python-list mailing list