Indexing
A string is a sequence of characters, and every character has a position, called its index. Square brackets pull one character out by its index.
Counting from the front
Positions start at 0, not 1:
word = "python"
print(word[0])
print(word[3])
word[0] is the first letter, word[3] is the fourth.
Counting from the back
A negative index counts from the end, starting at -1:
name = "Sanjin"
print(name[-1])
print(name[-2])
For a non-empty string, name[-1] gives the last character without needing to know the length. An empty string has no first or last character, so indexing it raises an error. Nickname Creator guarantees a non-empty name.
Slicing out a piece
Two numbers with a colon give you a slice: from the first index, up to but not including the second:
text = "programming"
print(text[0:4])
print(text[4:])
print(len(text))
Leaving the second number off means "to the end". len() counts the
characters.
Looping over the characters
for letter in "cat":
print(letter)
See also: String Formatting, String methods, Lists.
Your turn
Print the first character, then the last character, on separate lines.
word = "kangaroo"
# Add two print statements.
Expected output
k
o
Optional extension after reading about slices: print the first three characters. The expected result is kan.
The same positions work with lists
After reading Lists, use the same indexing rules for their items. The result is an item rather than a single character.
scores = [12, 8, 19]
print(scores[0])
print(scores[-1])
print(scores[0:2])
The outputs are 12, 19 and [12, 8]. A slice includes its start
position and excludes its stop position.
Stay within the sequence
For a non-empty sequence of length n, non-negative indexes run from
0 to n - 1. Using scores[len(scores)] raises IndexError.
An empty string or list has no item at 0 or -1.
Slices can extend beyond the end: scores[:100] returns the available
items. That does not make an individual out-of-range index valid.
A list is mutable, so scores[0] = 15 replaces an item. A string is
immutable: you cannot assign to word[0].
Dictionary keys are different
After reading Dictionaries, notice that
scores_by_name["Ada"] looks up a key, not a numbered position.
A dictionary key 0, if present, means that specific key, not the first item.
Your turn: index a list
Print the first item, the last item, and the first two items as a slice.
scores = [12, 8, 19]
# Add three print statements.
Expected output
12
19
[12, 8]
Practise this in the free Python course, where every exercise checks your code instantly.