Caio Scaravajar
Caio Scaravajar

Reputation: 94

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

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

Answers (4)

cards
cards

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

ramzeek
ramzeek

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

Woodford
Woodford

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

wim
wim

Reputation: 362557

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]

Upvotes: 1

Related Questions