Python String Slicing Stride Clarification

user995788 picture user995788 · Oct 14, 2011 · Viewed 22.1k times · Source

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"?

Answer

g.d.d.c picture g.d.d.c · Oct 14, 2011

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.