Check your understanding of the previous reading: string comparisons, membership, and subscripting/indexing.

Question 1

Assume the following code runs first: title = "Harry Potter". Which of these expressions evaluate to True?

Select every expression that is True, then check.

  • True. "word" is a substring of "The last word", right at the end.
  • False. The string only has a capital C, and in is case-sensitive, so lowercase "c" is not found.
  • False. "Harry Potter" does not contain the substring "it".
  • True. There is a space between "Harry" and "Potter".
  • True. The empty string is considered in every string.
  • True. 'A' comes before 'V' in the alphabet.
  • True. The two strings are equal, and <= also matches when both sides are equal.
  • True. Both sides are exactly the same string.
  • False. title ("Harry Potter") does appear inside "Harry Potter Book 1", so the not in test is False.

Question 2

Predict the output of the following code:

name = "Hermione"
print(name[0])

Show explanation

Indexing starts at 0, so name[0] is the very first character of "Hermione": H.

Question 3

Predict the output of the following code:

name = "Hermione"
print(name[4])

Show explanation

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.

Question 4

Predict the output of the following code:

name = "Hermione"
print(name[-2])

Show explanation

Counting from the back, name[-1] is the last character e, so name[-2] is the character just before it: n.

Question 5

Predict the output of the following code:

name = "Hermione"
print(name[:2])

Show explanation

Leaving out the start of a range means "from the beginning", so name[:2] grabs the first two characters: He.

Question 6

Predict the output of the following code:

name = "Hermione"
print(name[4:7])

Show explanation

Characters at index 4, 5 and 6 of "Hermione" are i, o and n, so name[4:7] is ion.

Question 7

Predict the output of the following code:

name = "Hermione"
print(name[-3:])

Show explanation

Leaving out the end of a range means "through the end", so name[-3:] grabs the last three characters: one.