Show Python string slicing with a start, a stop and a step, including negative indices.
A slice has the form text[start:stop:step]. The start is inclusive, the stop is exclusive, and the step controls the direction and the spacing.
text = "python"
print(text[0]) # p
print(text[0:3]) # pyt
print(text[2:]) # thon
print(text[:2]) # py
print(text[::2]) # pto
print(text[::-1]) # nohtyp
print(text[-2:]) # on
print(text[-3:-1]) # thReading the outputs: text[0:3] takes the first three characters, so pyt. Leaving the stop off means go to the end. Leaving the start off means start at zero. A step of 2 takes every second character, giving pto from the six-character string, and a step of -1 walks backwards, which is the standard way to reverse a string. The negative indices count from the end, so text[-2:] is the last two characters.
Two rules explain most slicing mistakes. First, the stop index is exclusive, unlike the inclusive ranges you might expect from an inclusive language. Second, an out-of-range slice does not raise an error — text[0:100] on a six-character string returns the whole string, and text[10:20] returns an empty string. Only indexing with a single out-of-range number raises IndexError, which is why a slice is safe to use on data of uncertain length.
The step being negative is also what makes the slice forms interchangeable with the common slicing idioms. text[::-1] is the reverse, text[:n] is the first n characters, text[-n:] is the last n, and text[1:-1] strips the first and last characters. Each of those is one operation with no intermediate copy beyond the result.