Skip to content

String indexing and slicing

Read characters with positive and negative indexes, take slices s and s, and predict each from a drawn index row.

It opens on

w = "computer". Its third letter is m. Is w[3] the letter m, or another one?

Why it matters

Text is everywhere in programs, from names and dates to file lines and DNA, and pulling out parts of it by position is the first string skill; the off-by-one at a slice's stop is a classic exam trap, and the same indexing works on lists next unit.

Good to know first

  • For loops and range: range(a, b) stops before b
  • Values, types and expressions: len and strings in quotes

Step by step

  1. Indexes

    Number a string's characters from 0 and from −1, and read one character with s[i].

    w[0] is c and w[3] is p, the fourth character, not m. The run printed c and p, which answers the opening question; m, the third letter, is w[2].

    A common mix-up

    The first character is w[1] and the last w[len(w)].

    In fact: Indexes start at 0, so the last is w[len(w) - 1], and w[len(w)] raises IndexError.

  2. Slices

    Take slices s, including with a start or stop left out or negative, and know that slices never raise IndexError.

    The run printed put, not "pute", since index 6, the e, is the stop and is left out. The length of a slice is b − a, here 3.

    A common mix-up

    w[3:6] includes the character at index 6.

    In fact: The stop is excluded, so it has indexes 3, 4 and 5 only.

  3. Steps and reversing

    Take slices with a step, s, including a negative step that reverses.

    w[::2] takes indexes 0, 2, 4 and 6, the c, m, u and e, so the run printed cmue.

    A common mix-up

    w[2:6:-1] gives the characters from 2 to 6 backwards.

    In fact: With a negative step the slice starts at 2 and moves down, so it never reaches 6, and the result is empty.

Try it

name = "Grace". What are name[0], name[-1] and name[2]?Answer

G, e and a

Hint: G is at 0

For date = "2026-12-01", which slice gives the month, and which the year?Answer

Date[5:7] gives "12", date[:4] gives "2026"

Hint: The dashes are at 4 and 7

For s = "abcdefgh", what are s[1:7:3] and s[::-2]?Answer

"be" and "hfdb"

Hint: Indexes 1 and 4; then 7, 5, 3, 1

What are w[-1] and w[-3]?Answer

r and t, the last and the third from last.

Which characters does w[3:6] give?Answer

Indexes 3, 4 and 5, which are p, u and t, so "put".

String indexing and slicing

30 minutes every month. No card.