🔤 Working with Text, lesson 2 of 5
Indexing and slicing
Pick out single characters and substrings by position.
10 min
2 exercises
2 quizzes
0/4 solved
Getting Python ready… examples can run in a moment.
Every character in a string has a position called an
index. Indexes start at 0, and negative indexes
count from the end, starting at -1. Use square
brackets to get one character: word[0].
Two ways to count: word = "Python"
Every character has two indexes: one counting from 0 at the front, and a negative one counting from -1 at the back.
Single characters
Try word[6]. There is no index 6, so Python raises an IndexError.
What does this print?
A slice text[start:stop] takes the characters
from start up to, but not including, stop.
- Leave out
startto begin at the start:text[:3] - Leave out
stopto go to the end:text[3:] - Negative indexes work too:
text[-3:]is the last 3 characters - Add a step:
text[::2]takes every 2nd character, andtext[::-1]reverses the string
Slicing word = "Python"
Start at index 0 and stop before index 2. The slice has 2 - 0 = 2 characters.
Slices
With the default step of 1, non-negative indexes, and start <= stop <= len(word), a slice has stop - start characters: word[2:5] has 3. The shortcut breaks for steps, negative indexes, and a stop past the end — word[::2] has 3 characters, not 6 - 0 = 6, and word[3:10] has 3, not 7 — so count (or use len()) there.
What does this print?
Slice it up
Using indexes and slices of word, set:
firstto the first letterlastto the last lettermiddleto everything except the first and last letters
Palindrome peek
Store word reversed in backwards using a slice.
(A palindrome reads the same both ways, like
"racecar". Try other words after checking!)