Assuming we have the following string:
> x = "hello world"
we can reverse it like this:
> x[::-1] 'dlrow olleh'
The extended slice operator explained
The extended slice specifies a beginning, end, and step. Beginning is the place to begin in the sequence. End is the place to stop in the sequence. This allows you to slice off a portion of a sequence.
For the string
x = "hello world"
We can get the 2 - 5 characters like this:
Notice that this starts after the second character as the index starts at 0, and it ends after the fifth character producing:
To match our example, leaving the begining and end values empty means that we start at the beginning of the sequence and end at the end. Basically it includes the entire sequence.
Step refers to how we will step through the sequence. If step is -1 then we are stepping through the sequence in reverse hitting every element. If step is 5, then we are moving through the sequence hitting every fifth element.
So using this:
means that we include the entire string and step through backwards ultimately reversing the string.
reversed function is a built-in function that takes an iterable and returns a "reversed" iterator.
Again, let's take our "hello world" string as an example:
> x = 'hello world'
We can reverse it like so:
> ''.join(reversed(x)) 'dlrow olleh'
reversed function explained
reversed function takes an iterable and returns a reverse iterator. If you simply called
reversed on a string, you'll see the iterator object:
> reversed('hello world') <reversed at 0x10f583400>
This behaves like a normal iterator, so you can cast it as a
list or use it in a
for loop or use
join to turn it into a string.