How does string slicing work in Python, and what do negative indices mean?
s[start:stop:step] takes characters from start up to but not including stop. Negative indices count from the end, so s[-1] is the last character. Out-of-range slice bounds are clamped and never raise an error.
Explain it simply
Picture the characters standing in a queue with fences between them. The fences are numbered from 0 on the left. A slice cuts between two fences, so the stop fence is not included. Negative numbers count the fences from the right end.
Example
s = "PYTHONISTA"
print(s[0]) # Output: P
print(s[-1]) # Output: A
print(s[2:5]) # Output: THO
print(s[:3]) # Output: PYT
print(s[-3:]) # Output: STA
print(s[::2]) # Output: PTOIT
print(s[::-1]) # Output: ATSINOHTYP
print(s[3:100]) # Output: HONISTAIndexing a single position that does not exist, like s[50], raises IndexError, but slicing past the end quietly stops at the end.
What to say in the interview
"Slices are s[start:stop:step] with stop exclusive. Negative indices count from the right, with -1 as the last item. Missing bounds default to the ends, a negative step walks backwards, and out-of-range slices are clamped instead of raising. A slice always creates a new string."
Common mistakes
- Using
s[-0]for the last character;-0is just0. - Forgetting that stop is exclusive, which causes off-by-one errors.