Slices
You can read one character of a text by its index: word[0]. With a slice, you read a whole part of it at once. In the square brackets, write two indexes with a colon between them: where the part starts and where it stops.
word = "Python"
print(word[0:4])
print(word[2:5])This prints:
Pyth
thoThe character at the stop index is not included, just as range(0, 4) stops at 3. word[0:4] gives the characters at indexes 0, 1, 2 and 3: four characters. That's handy, because the stop minus the start is the length of the slice.
You can leave out either index. Without the start, the slice starts at the beginning; without the stop, it goes to the end. And negative indexes count from the end, as you know:
word = "Python"
print(word[:3])
print(word[2:])
print(word[-3:])This prints:
Pyt
thon
honword[:3] is the first three characters, word[2:] everything from index 2 on, and word[-3:] the last three characters.
Slices work on lists too, and they give a new list. When a list of scores is in order from the best, its top three are scores[:3]:
scores = [98, 91, 85, 77, 60]
print(scores[:3])
print(scores[-2:])This prints:
[98, 91, 85]
[77, 60]Unlike a single index, a slice never ends with an IndexError. If it reaches past the end, you simply get what there is: "Hi"[:10] is "Hi", and [98, 91][:3] is [98, 91]. So scores[:3] works even when there are fewer than three scores.
And like the methods in this lesson, a slice doesn't change the original. It returns a new text or a new list.
Instructions
- 1
The variable
dateholds a date written as year-month-day. Use slices to print it the way it's written in the United States, month/day/year:11/26/2026. Keep the lines withdateandscores: the exercise also tries other values in them. - 2
The list
scoresholds the best scores of a game, from the best. Print the top three:[98, 91, 85].