Reputation: 94
I'm trying to convert a string-like interval (example: '1:10') to a useful integer interval (example: 1:10). The point is that my methods aren't working. I tried to refer to the string interval and it didn't work:
x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
string_interval = '0:4'
x[string_interval]
Desired output:
1, 2, 3, 4, 5
I also tried to convert the string_interval to an integer with int() but it didn't work too.
Upvotes: 2
Views: 649
Reputation: 4965
You can make a string like command and the evaluate it.
x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
string_interval = '0:4'
x_str = f'x[{string_interval}]'
x_cmd = eval(x_str)
print(x_cmd) # it is still a list object`
Output
[1, 2, 3, 4] #0:4 interval
Upvotes: 0
Reputation: 2315
Are you looking for eval: print(eval('x[%s]' % string_interval)) #[1,2,3,4]
Also note that you need string_interval='0:5'
to get [1,2,3,4,5] as you're basically giving it a range.
Upvotes: 0
Reputation: 4439
>>> idx = string_interval.split(':')
>>> x[int(idx[0]):int(idx[1])+1]
[1, 2, 3, 4, 5]
Add 1 to the ending index because slices in Python go up to, but don't include the value at the ending index.
Upvotes: 1