Python String Indexing and Slicing
Core idea
An index is a position in a sequence. Python starts counting at zero, so text[0] reads the first code point. A negative index counts from the end: text[-1] reads the last. len(text) gives the number of code points, not necessarily the number of visible letters or bytes.
The indices of this six-character ASCII string run from 0 to 5; -1 refers to position 5.
Extract a range
code = "AB-729"print(code[3:6])print(code[:2])print(code[-3:])print(code[3:99])A slice text[start:stop] includes start and excludes stop. Omitted bounds mean the beginning or end. A slice beyond the end is clipped rather than raising an index error.
Intentional error: missing position
There are only two positions, 0 and 1, so index 2 raises IndexError. An empty string has no valid character index.
Common mistake
Do not include the stop index in the result. For example, text[1:3] reads positions 1 and 2, not position 3.
Practice
Given code = "XY-248", extract the three digits and then the two-letter prefix. Predict each result before printing.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Indexing and slicing
Check your understanding of indexing and slicing.
What is printed?
print("pet"[1])What is printed?
print("abcde"[1:3])What happens when the code runs?
print("x"[1])Which slice extracts the last two code points of a string called text?