Indexing and Slicing


One of the most used features of Python is indexing and slicing. These are the acts of accessing the characters in the string by position, assuming you are doing it to a string.

The first index s[0] gets the item at offset 0 from the left, while s[-1] gets the item from offset 1 from the end.


Slicing returns an entire section instead of one single item.

You could think of it like this: s[START:END]. Give me the string omitting before and up to, not including START index ... and omit END and after it. If no START, then give me all the way from beginning, if no END give me all the way to the end. Slicing will get easier the more you use it.

Not as if you are already confused, but there is also a third index in the slice s[START:END:STEP]. This STEP index will allow you to get the sliced string by skipping STEP. For example, a step of 2 will give you every other index based on your values of START and END.

This slice is saying we want index 2 through 19 at intervals of 2.

In the same token we can use this to reverse the order of the string.