String Indexing & Slicing - Python

  1. Which expression raises an exception?
    Answer: "hello"[5] "hello" has indices 0 to 4, so indexing at 5 raises IndexError. Slices never raise for out-of-range bounds: "hello"[5:] simply returns an empty string.
  2. Given s = "abcdefg", which expression produces "cde"?
    Answer: s[2:5] Indexing starts at 0, so 'c' is at 2. The stop is excluded, so s[2:5] takes indices 2, 3 and 4: "cde". s[2:4] stops before 'e' and gives only "cd".
  3. What does this print? print("abcdef"[4:1:-1])
    Answer: edc With step -1 the slice starts at index 4 ('e') and moves left, stopping before index 1. That gives 'e', 'd', 'c': "edc". "edcb" wrongly includes the stop index.
  4. String s has length n, and 1 <= k <= n. Which index always gives the same character as s[-k]?
    Answer: s[n-k] Python converts a negative index by adding the length, so -k becomes n-k. For example, -1 becomes n-1, the last character. s[n-k-1] is off by one and points one character too far left.
  5. What does this print? print("python"[-4:-1])
    Answer: tho -4 is 't' (index 2) and -1 is 'n' (index 5), which is excluded. The slice covers indices 2 to 4: "tho". "thon" wrongly includes the stop index.

Start this quiz