Indexing and slicing
🌍 In real life. A train at the station is a row of coaches. To tell someone where to board, you give a coach number. And to describe part of the train, you might say "coaches 1 to 3". Python numbers the characters of a string the same way, with one twist: it starts counting at 0.
The idea in one sentence: each character has a position number, its index, starting at 0; word[i] picks one character and word[start:stop] picks a piece up to, but not including, stop.
Its words:
- index: a character's position: 0 for the first, 1 for the second, and so on
- negative index: counts from the end: -1 is the last character
- slice: a piece of a string,
word[start:stop] - step: a third number in a slice,
word[::2], that jumps over characters
Step by step, for word[2] when word is "PYTHON":
- Count from 0: P is 0, Y is 1, T is 2.
- So
word[2]is'T'.
word = "PYTHON"
print(word[0])
print(word[2])
print(word[5])Negative indexes count from the end: word[-1] is the last character and word[-2] is the one before it. They're handy when you don't know how long the string is.
word = "PYTHON"
print(word[-1])
print(word[-3])A slice takes a piece of the string. word[start:stop] goes from start up to, but not including, stop. Leave a number out to go all the way to that end: word[:2] or word[3:].
word = "PYTHON"
print(word[1:4])
print(word[:2])
print(word[3:])
print(word[::-1])Why the stop is left out. It makes the maths tidy:
- a slice
word[start:stop]has exactlystop - startcharacters, soword[1:4]has 3 word[:k] + word[k:]is always the whole word: nothing is lost or counted twice- a slice never goes out of range:
word[2:100]simply stops at the end
What it costs. Picking one character with word[i] is instant, however long the string is: Python jumps straight to position i. A slice copies its characters into a new string, so a longer slice takes longer.
Strings can't be changed. You can't change one character of a string in place: word[0] = "J" is an error. Build a new string instead:
word = "PYTHON"
new_word = "J" + word[1:]
print(new_word)Mistakes and edge cases.
- Using the length as an index. "PYTHON" has 6 characters, so the last index is 5.
word[6]givesIndexError: string index out of range(see below). - Counting from 1.
word[1]is the second character. - Changing a character.
word[0] = "J"givesTypeError: 'str' object does not support item assignment. - Forgetting the stop is left out.
word[1:3]is 2 characters,'YT', not 3. - Start after stop.
word[4:1]is'', an empty string, with no error.
word = "PYTHON"
print(word[6])Quiz
What does this print?
s = "HELLO" print(s[1])What does this print?
s = "HELLO" print(s[-1])What does this print?
s = "HELLO" print(s[1:3])What does this print?
s = "HELLO" print(s[:3])What does this print?
s = "abc" print(s[::-1])Which line causes an error?
s = "cat" print(s[0]) print(s[3])
Coding tasks
nameholds"Bangladesh". Makefirsthold its first letter andlasthold its last letter.textholds"sunflower". Makeflowerhold"flower"using a slice.wordholds"level". PrintTrueif the word reads the same backwards. Use[::-1]and==.