🔤 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:
P y t h o n
0 1 2 3 4 5
-6 -5 -4 -3 -2 -1
Use square brackets to get one character: word[0].
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:] - Add a step:
text[::2]takes every 2nd character, andtext[::-1]reverses the string
Slices
The length of a slice is stop - start: word[2:5] has 3 characters.
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!)