Strings: Indexing, Slicing and Length · seed 1 · A4, ink-friendly. The answer key prints on its own page for grown-ups.

Text by the numbers

Computing · Programming · ages 15-16
Name ______________________   Date ____________
  1. What does a slice copy?

    • Characters from its start through its stop
    • Characters from its start up to, but not including, its stop
    • Only the character at its stop
  2. In most languages, what seat number does the first character of a string sit in?

    • 0
    • 1
    • -1
  3. len() counts spaces as well as letters.

    Circle one:   True   False

  4. name holds "Ada". What does name[-1] give?

    • A
    • d
    • a
  5. phone holds "02079460018". What does phone[0:3] give?

    • 0207
    • 020
    • 207
  6. How many characters are in "Hi Jo"?

    Answer: ______________

  7. A word has length 5. Which test keeps a loop on real seats only?

    • seat < 5
    • seat <= 5
    • seat < 4
  8. A program reads word[4] from a 4-character word and crashes. What went wrong?

    • The word is too short for len()
    • Seat 4 holds an invisible space
    • Seats run 0 to 3, so seat 4 does not exist
LightMySky · lightmysky.comW1-mt_33hA050_Qz-s1

Answer key

For grown-ups. Fold this page away before handing over the rest.

Text by the numbers W1-mt_33hA050_Qz-s1

  1. Characters from its start up to, but not including, its stop · A slice starts at its first number and stops just before its last number.
  2. 0 · Counting starts at 0, so the first character lives at index 0.
  3. True · Every character counts toward the length, including spaces.
  4. a · -1 counts back from the end, so it grabs the last character.
  5. 020 · Seats 0, 1 and 2 hold 0, 2 and 0, and the slice stops before seat 3.
  6. 5 · Two letters, a space, then two letters make 5 in total.
  7. seat < 5 · Seats run 0 to 4, so stopping below 5 visits each real seat once.
  8. Seats run 0 to 3, so seat 4 does not exist · With length 4 the seats are 0, 1, 2 and 3. Reaching for seat 4 is one too far.
Worksheet · LightMySky