Python Slicing Exercises
Let’s check out some exercises that will help you understand and master how Python’s Slice Notions, Slicing and Advanced Slicing works.
Exercise 17-a
Slice the word until first "a". (Tosc)
Exercise 17-b
Slice the word so that you get "cana".
Exercise 17-c
Now try to get "can" only.
Exercise 17-d
Can you slice the word from beginning to the end with steps of 2 (including the last character.)?
[start:stop] notation can be used to slice a Python string.
Just keep in mind that in [start:stop] notation, stop value won’t be included. So, you need to type the index of the last value you’d like to include +1.
If you omit the parameter before the colon (:) It will mean all the way for that parameter.
So, [:3:1], here first colon has no parameter which means all the way from the beginning. And, [0::1] here second colon has no parameter which means all the way to the end.
ans_1 = wrd[::2]
or
ans_1 = wrd[0::2]
Exercise 17-e
Now slice the word with steps of 2, excluding first and last characters.
Exercise 17-f
Can you slice the list so that it's reversed without using the .reverse() method?
Exercise 17-g
Slice the list so that only last 2 elements are included.
Exercise 17-h
Slice the second and third elements (50 and 20) in the list.