9.3. Index Operator: Working with the Characters of a String

The indexing operator (Python uses square brackets to enclose the index) selects a single character from a string. The characters are accessed by their position or index value. For example, in the string shown below, the 15 characters are indexed left to right from postion 0 to position 14.

index values

It is also the case that the positions are named from right to left using negative numbers where -1 is the rightmost index and so on. Note that the character at index 7 (or -8) is the blank character.

The expression school[2] selects the character at index 2 from school, and creates a new string containing just this one character. The variable m refers to the result.

Remember that computer scientists often start counting from zero. The letter at index zero of "Roanoke College" is R. So at position [2] we have the letter a.

If you want the zero-eth letter of a string, you just put 0, or any expression with the value 0, in the brackets. Give it a try.

The expression in brackets is called an index. An index specifies a member of an ordered collection. In this case the collection of characters in the string. The index indicates which character you want. It can be any integer expression so long as it evaluates to a valid index value.

Note that indexing returns a string — Python has no special type for a single character. It is just a string of length 1.

Check your understanding

    strings-4-1: What is printed by the following statements?

    s: str
    s = "python rocks"
    print(s[3])
    
  • t
  • Index locations do not start with 1, they start with 0.
  • h
  • Yes, index locations start with 0.
  • c
  • s[-3] would return c, counting from right to left.
  • Error, you cannot use the [ ] operator with a string.
  • [ ] is the index operator

    strings-4-2: What is printed by the following statements?

    s = "python rocks"
    print(s[2] + s[-5])
    
  • tr
  • Yes, indexing operator has precedence over concatenation.
  • ps
  • p is at location 0, not 2.
  • nn
  • n is at location 5, not 2.
  • Error, you cannot use the [ ] operator with the + operator.
  • [ ] operator returns a string that can be concatenated with another string.
You have attempted of activities on this page
9.2. Operations on Strings"> 9.4. Length">Next Section - 9.4. Length