# 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 length. Give it a try in the example above.

Typically, a Python programmer will access the last character by combining the two lines of code from above.

lastch = fruit[len(fruit)-1]


rec-5-16: What is printed by the following statements?

s = "python rocks"
print len(s)

• (A) 11
• The blank space counts as a character.
• (B) 12
• Yes, there are 12 characters in the string.

rec-5-17: What is printed by the following statements?

s = "python rocks"
print s[len(s)-5]

• (A) o
• Take a look at the index calculation again, len(s)-5.
• (B) r
• Yes, len(s) is 12 and 12-5 is 7. Use 7 as index and remember to start counting with 0.
• (C) s
• s is at index 11
• (D) Error, len(s) is 12 and there is no index 12.
• You subtract 5 before using the index operator so it will work.

Note

You can leave out len(s) entirely in the above expression and get the same result using negative indexing (i.e., try replacing the last line with print s[-5]. This offers another intuition for why negative indexing starts at -1 rather than at -0.

Next Section - The Slice Operator