Check your understanding of the previous reading: string comparisons, membership, and subscripting/indexing.
Predict the output of the following code:
name = "Hermione"
print(name[0])
Indexing starts at 0, so name[0] is the very first character of "Hermione": H.
Predict the output of the following code:
name = "Hermione"
print(name[4])
Counting from 0, "Hermione" is H(0) e(1) r(2) m(3) i(4) o(5) n(6) e(7), so name[4] is i.
Predict the output of the following code:
name = "Hermione"
print(name[-2])
Counting from the back, name[-1] is the last character e, so name[-2] is the character just before it: n.
Predict the output of the following code:
name = "Hermione"
print(name[:2])
Leaving out the start of a range means "from the beginning", so name[:2] grabs the first two characters: He.
Predict the output of the following code:
name = "Hermione"
print(name[4:7])
Characters at index 4, 5 and 6 of "Hermione" are i, o and n, so name[4:7] is ion.
Predict the output of the following code:
name = "Hermione"
print(name[-3:])
Leaving out the end of a range means "through the end", so name[-3:] grabs the last three characters: one.