9.4. Length

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

 
1
fruit: str
2
fruit = "Banana"
3
print(str(len(fruit)))
4

(chp08_len1)

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

9
 
1
fruit: str
2
size: int
3
last: str
4
5
fruit = "Banana"
6
size = len(fruit)
7
last = fruit[size]       # ERROR!
8
print(last)
9

(chp08_len2)

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.

9
 
1
fruit: str
2
size: int
3
last: str
4
5
fruit = "Banana"
6
size = len(fruit)
7
last = fruit[size - 1]
8
print(last)
9

(ch08_len3)

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)))



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

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





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

s: str
s = "python rocks"
print(s[-3])





You have attempted 1 of 7 activities on this page
Next Section - 9.5. String Comparison