Python: want to use string as a slice specifier

Suppose I have a variable S with string "1:3" (or, for that matter, "1" or "1:" or ":3" ), and I want to use this as a slice specifier in list L You cannot just do L[S] , since the required arguments to slice are "int:int" .

Now I have some ugly code that parses S into two components of int and deals with all cases of edges (4 of them) to come up with the correct access to the slice, but it is just ugly and unpythonic.

How do I elegantly take the string S and use it as my slice specifier?

+4
source share
2 answers

Here is another solution

 eval("L[%s]" % S) 

warning - This is unsafe if S comes from an external (unreliable) source.

+1
source

This can be done without a big hack using list comprehension. We split the line into : by passing the separated elements as arguments to the built-in slice() . This allows us to do a pretty good slice on one line, in a way that works in every case that I can think of:

 slice(*[int(i.strip()) if i else None for i in string_slice.split(":")]) 

Using the built-in slice() , we carefully avoid dealing with too many cases with edges.

Usage example:

 >>> some_list = [1, 2, 3] >>> string_slice = ":2" >>> some_list[slice(*[int(i.strip()) if i else None for i in string_slice.split(":")])] [1, 2] >>> string_slice = "::-1" >>> some_list[slice(*[int(i.strip()) if i else None for i in string_slice.split(":")])] [3, 2, 1] 
+5
source

Source: https://habr.com/ru/post/1445236/


All Articles