Skip to main content

Section 7.2 Getting the length of a string using len()

len() is a built-in function that returns the number of characters in a string:

Checkpoint 7.2.1.

    11-9-2: What is printed by the following statements?
    street = "125 Main Street"
    print(len(street))
    
  • 13
  • Incorrect! Don't forget to include the spaces in the count. Try again.
  • 15
  • Correct! The len function returns the number of characters in the string, including spaces.
  • 10
  • Incorrect! This would be true if the len function only returned the number of different characters present, but it includes all characters, including spaces. Try again.
  • 6
  • Incorrect! This is the length of the word "street", not the length of the string named street. Try again.
To get the last letter of a string, you might be tempted to try something like this:
The reason for the IndexError is that there is no letter in “banana” with the index 6. Since we started counting at zero, the six letters are numbered 0 to 5. To get the last character, you have to subtract 1 from length:
Alternatively, you 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.

Checkpoint 7.2.2.

    11-9-5: What is printed by the following statements?
    s = "green apples"
    print(s[len(s)-5])
    
  • l
  • Incorrect! Take a look at the index calculation again. Try again.
  • p
  • Correct! Yes, len(s) is 12 and 12-5 is 7. Index 7 of s is 'l'.
  • a
  • Incorrect! 'a' is at index 6. Try again.
  • Error, len(s) is 12 and there is no index 12.
  • Incorrect! You subtract 5 before using the index operator, so there isn't an error. Try again.

Checkpoint 7.2.3.

    11-9-6: What is printed by the following statements?
    s = "python rocks"
    print(s[-3])
    
  • c
  • Correct! 'c' is three characters from the end of the string.
  • k
  • Incorrect! s[-3] means to use the third to last character. Try again.
  • s
  • Incorrect! When expressed with a negative index, 's' is at index -1. Try again.
  • Error, negative indices are illegal.
  • Incorrect! Python uses negative indices to count backwards from the end. Try again.