So I don't really get the deal with the stride parameter in slicing.
For example, "123456"[::-2]
produces "642"
, but why does "123456"[1::-2]
produce "2"
and "123456"[2::-2]
produce "31"
?
String slicing can accept a third parameter in addition to two index numbers. The third parameter specifies the stride, which refers to how many characters to move forward after the first character is retrieved from the string.
Second note, when no start is defined as in A[:2] , it defaults to 0. There are two ends to the list: the beginning where index=0 (the first element) and the end where index=highest value (the last element).
When a negative stride is specified for a vector, the location specified for the vector is actually the location of the last element in the vector. In other words, the vector is in reverse order in the array: (xn, xn-1, …, x1).
UNDERSTANDING SLICING The index 5 will not be included. One way to remember this is that the start point is inclusive and the end point is exclusive. In other words the slice will be from the start point up to but not including the end point.
The easiest way to explain is probably to address your examples:
"123456"[::-2] # This takes the whole string ([::]) # Then it works backward (-) # and it does every other character (2) "123456"[1::-2] # This is also working backward (-) # every other character (2) # but starting at position 1, which is the number 2. "123456"[2::-2] # Again, working backward (-) # Every other character (2) # begin at position 2, so you end up with positions 2, and 0, or '31'
The slicing syntax is [<start>:<end>:step]
. If <start>
is omitted and the step is negative then it starts at the end of the string.
That's because the syntax is string[start:end:step]
"123456"[::-2]
Produces "642" because it'll start from the last character. This is because you didn't provide from which position the slice would be executed. So it'll go back by 2 characters from the last one until it reaches the first one.
"123456"[1::-2]
Produces "2" because you told Python to start from the 2nd character (index 1 from the string) and you told Python to go back 2 steps from that position. Which in this case, Python would obviously return just "2". This is because when Python tried to go back by 2 steps, it already hit the first character in the string with just one step.
"123456"[2::-2]
You should be able to figure this one out by now. But I'll just explain it anyway. So, you told Python to start from the third character (or index 2) and then go back 2 steps from there until it reaches the first character. So it'll start from "3" and then go back 2 steps, and accidentally the first character - which happens to be "1" - has been reached. So Python will give you "31"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With