Indexing and slicing
Grab characters and pieces of a string
A string is a sequence of characters in a fixed order. Because the order is fixed, you can ask Python for "the first character" or "characters 2 to 5". That's indexing and slicing.
Every character has a position
Each character has a number called its index. Python starts counting at 0, not 1.
Indexing: one character
Put the index in square brackets after the string.
word = "PYTHON"
print(word[0]) # P (first)
print(word[3]) # H
print(word[-1]) # N (last)
print(word[-2]) # O (second from the end)-1 whenever you want the last item. You don't need to know how long the string is.Slicing: a piece of the string
A slice uses a colon: text[start:stop]. It includes start but stops before stop.
word = "PYTHON"
print(word[0:2]) # PY
print(word[2:5]) # THO
print(word[:3]) # PYT (from the beginning)
print(word[3:]) # HON (to the end)
print(word[-3:]) # HON (last three characters)Adding a step
A third number sets the step size. A step of -1 walks backwards, which reverses the string.
word = "PYTHON"
print(word[::2]) # PTO (every second character)
print(word[::-1]) # NOHTYP (reversed)Real example: trimming long text
AI programs often show a short preview of a long answer or document. Slicing makes that a one-liner.
answer = "Python is a popular programming language used for AI, data science, and automation."
preview = answer[:30] + "..."
print(preview)
# Python is a popular programmi...Strings can't be changed in place
You can read a character by index, but you can't replace it. Strings are immutable. Build a new string instead.
word = "cat"
# word[0] = "b" # TypeError!
word = "b" + word[1:]
print(word) # batCommon mistakes
- Forgetting that counting starts at 0, so
word[1]is the second character. - Expecting the stop index to be included.
word[0:3]gives three characters: 0, 1 and 2. - Using an index that's too big:
"abc"[5]raises anIndexError. Slices never raise this error."abc"[0:50]just returns"abc".
What's next?
The same indexing and slicing rules also work for lists. Next, you'll learn how to convert values between types, for example turning the text "42" into the number 42.