Reputation: 8384
It's possible to slice a python list like this:
>>> list=['a', 'b']
>>> list[0:1]
['a']
However, when passing the index as a string, an error is thrown:
>>> index="0:1"
>>> list[index]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: list indices must be integers, not str
How can I specify a list index as a string? What data type is 0:1
in list[0:1]
, really?
Upvotes: 0
Views: 1182
Reputation: 1
Use the [ : ] where you specify the start point and end point ,so you can easily trace what you intend to slice
Upvotes: 0
Reputation: 82899
n:m
is syntactic sugar for a slice
. You could split
your index string, convert its parts to integers, and create a slice
from those.
>>> lst = list(range(10))
>>> index = "1:4"
>>> s = slice(*map(int, index.split(':')))
>>> lst[s]
[1, 2, 3]
Works just the same with three parts:
>>> index = "1:9:2"
>>> s = slice(*map(int, index.split(':')))
>>> lst[s]
[1, 3, 5, 7]
If you want to allow for "blank" parts, the conversion gets a little bit more involved:
>>> index = "::-1"
>>> s = slice(*[int(x) if x else None for x in index.split(':')])
>>> lst[s]
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
Upvotes: 7
Reputation: 10789
You can use exec()
for this.
l = ['a', 'b']
index="0:1"
exec('print(l[{}])'.format(index))
The print is needed only to see the output. You can assign it to a variable and call the variable afterwards instead.
Upvotes: 1
Reputation: 17582
Why not just convert your slicing string into integers by splitting on :
, and then using them as slicing indices.
list=['a', 'b']
slicer_str = '0:1'
slicer_int = [int(i) for i in slicer_str.split(':')]
print(list[slicer_int[0]:slicer_int[1]])
Upvotes: 1