The optional, third number in a slice specifies the stride. If omitted, the default is 1: return every character in the requested range. To return every $k$th letter, set the stride to k
. Negative values of k
reverse the string. For example,
>>> s = 'King Arthur'
>>> s[::2]
'Kn rhr'
>>> s[1::2]
'igAtu'
>>> s[-1:4:-1]
'ruhtrA'
This last slice can be explained as a selection of characters from the last (index -1
) down to (but not including) character at index 4
, with stride -1
(select every character, in the reverse direction).
A convenient way of reversing a string is to slice between default limits (by omitting the first and last indexes) with a stride of -1
:
>>> s[::-1]
'ruhtrA gniK'