How to convert list intervals (in string format) to integers?

Viewed 129

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.

4 Answers

You can use a slice instance:

>>> x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> string_interval = '0:4'
>>> item = slice(*map(int, string_interval.split(":")))
>>> x[item]
[1, 2, 3, 4]
>>> 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.

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

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.

Related