I’m trying to use values in list to select part of word. Here is working solution:
JavaScript
x
11
11
1
word = 'abc'*4
2
slice = [2,5] #it can contain 1-3 elements
3
4
def try_catch(list, index):
5
try:
6
return list[index]
7
except IndexError:
8
return None
9
10
print(word[slice[0]:try_catch(slice,1):try_catch(slice,2)])
11
but I wonder if is it possible to shorten it? Something like this comes to my mind:
JavaScript
1
4
1
word = 'abc'*4
2
slice = [2,6,2]
3
print(word[':'.join([str(x) for x in slice])]) #missing : for one element in list
4
It produces:
JavaScript
1
2
1
TypeError: string indices must be integers
2
Advertisement
Answer
You can use the built-in slice
(and need to name your list differently to be able to access the built-in):
JavaScript
1
5
1
>>> word = 'abcdefghijk'
2
>>> theslice = [2, 10, 3]
3
>>> word[slice(*theslice)]
4
'cfi'
5