Reversing a String Using a Slice
00:10 What exactly does this mean? The term immutable describes an object whose state or value cannot be changed after it has been created. This means that every modification to an object will result in a new object.
00:23 This has interesting performance implications that will pop up later in the course. The term sequence refers an ordered collection of elements—in this case, characters. Therefore, in plain English, a string is described as an unchanging ordered collection of characters.
.__getitem__() is the recommended way to access those elements by index or key. Magic methods are not usually called directly. In the case of the
.__getitem__() method, the square bracket operator (
) is usually used.
step argument then defines the fixed interval at which the items are indexed. If
start is not provided, it’s set to
0, referring to the index of the first element of your sequence object. Similarly, if
stop is not provided, it is set to the final element of your sequence. If
step is not provided, it defaults to
1, meaning every element between
stop is indexed.
For example, using the same string as before, you can try passing a
5, and a
1, which should index the first five characters with an interval of one—in this case,
step is by default
1, you don’t have to specify it, and you can simply write
Finally, just to show that all the arguments are optional, if you just pass
[::] to the bracket operator, the entire string is returned. I recommend experimenting with different sequence types such as lists, as well as different arguments to the bracket operator.
step has a special behavior for negative values. When the values are negative,
step operates on the string in reverse order, indexing every nth element between
start backwards, where n is the value of
step. Setting the
1 would select all the elements between
stop, as we’ve seen before.
Setting it to
-1 does the exact same but in reverse order. Therefore, using a
-1 will select all characters between
stop in reverse. If
stop are left to their respective defaults, the entire sequence is selected in reverse.
Become a Member to join the conversation.