Execute Program

Python for Programmers: Strings as Collections

Welcome to the Strings as Collections lesson!

This lesson is shown as static text below. However, it's designed to be used interactively. Click the button below to start!

  • Strings behave like lists in some ways. For example, we can index into them using the familiar indexing syntax.

  • Unlike some programming languages, Python doesn't have a dedicated character data type. When we index into a string, we get another string containing only that character.

  • >
    "cat"[1]
    Result:
    'a'Pass Icon
  • This has one strange side effect. We can index into a string, giving us a single-character string. Then we can index into that single-character string at index 0, giving us the same single-character string again. Each time we index into the string, we get a string of length 1.

  • >
    "cat"[1][0]
    Result:
    'a'Pass Icon
  • >
    "cat"[2][0][0][0][0][0][0]
    Result:
    't'Pass Icon
  • When we index outside of a string, Python raises an IndexError.

  • >
    "cat"[3]
    Result:
    IndexError: string index out of rangePass Icon
  • >
    "cat"[0]
    Result:
    'c'Pass Icon
  • >
    "cat"[0][1]
    Result:
    IndexError: string index out of rangePass Icon
  • Strings support slices, which we already saw for lists. In the next example, our string has a fixed format: "Ticket #" followed by a four-digit number. We use the slice syntax to extract just the number part.

  • >
    ticket = "Ticket #1234"
    id = ticket[-4:]
    id
    Result:
    '1234'Pass Icon
  • Slicing out of bounds gives us an empty string. This matches what we already saw for lists, where slicing out of bounds gives us an empty list.

  • >
    data = "abc"
    data[10:15]
    Result:
    ''Pass Icon
  • string1 in string2 tells us whether a string contains another string.

  • >
    friends = "Betty, Cindy, Dalili"
  • Note: this code example reuses elements (variables, etc.) defined in earlier examples.
    >
    "Betty" in friends
    Result:
    TruePass Icon
  • Note: this code example reuses elements (variables, etc.) defined in earlier examples.
    >
    "Cindy" in friends
    Result:
    TruePass Icon
  • Note: this code example reuses elements (variables, etc.) defined in earlier examples.
    >
    "Amir" in friends
    Result:
    FalsePass Icon
  • As usual, we can invert the in operator with string1 not in string2.

  • Note: this code example reuses elements (variables, etc.) defined in earlier examples.
    >
    "Ebony" not in friends
    Result:
    TruePass Icon