9.4. Length

The len function, when applied to a string, returns the number of characters in a string.

To get the last letter of a string, you might be tempted to try something like this:

That won’t work. It causes the runtime error IndexError: string index out of range. The reason is that there is no letter at index position 6 in "Banana". Since we started counting at zero, the six indexes are numbered 0 to 5. To get the last character, we have to subtract 1 from the length. Give it a try in the example above.

Alternatively in Python, we can use negative indices, which count backward from the end of the string. The expression fruit[-1] yields the last letter, fruit[-2] yields the second to last, and so on. Try it! Most other languages do not allow the negative indices, but they are a handy feature of Python!

Check your understanding

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

    s: str
    s = "python rocks"
    print(str(len(s)))
    
  • 11
  • The blank counts as a character.
  • 12
  • Yes, there are 12 characters in the string.

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

    s: str
    s = "python rocks"
    print(s[len(s) - 5])
    
  • o
  • Take a look at the index calculation again, len(s)-5.
  • r
  • Yes, len(s) is 12 and 12-5 is 7. Use 7 as index and remember to start counting with 0.
  • s
  • s is at index 11
  • Error, len(s) is 12 and there is no index 12.
  • You subtract 5 before using the index operator so it will work.

    strings-6-3: What is printed by the following statements?

    s: str
    s = "python rocks"
    print(s[-3])
    
  • c
  • Yes, 3 characters from the end.
  • k
  • Count backward 3 characters.
  • s
  • When expressed with a negative index the last character s is at index -1.
  • Error, negative indices are illegal.
  • Python does use negative indices to count backward from the end.
You have attempted of activities on this page
9.3. Index Operator: Working with the Characters of a String"> 9.5. String Comparison">Next Section - 9.5. String Comparison