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]
source share