Getting the length of a string using LEN()

Len is a built-in function that returns the number of characters in a string:
>>>word = ‘hello’
>>>len(word)
5
To get the last letter of a string, you might be tempted to try something like this:
>>>length=len(word)
>>>last = word[length]
Traceback (most recent call last):
  File "", line 1, in 
IndexError: string index out of range
The reason for the IndexError is that there is no letter in ‘word’ with the index 5. Since we started counting at zero, the five letters are numbered from 0 to 4. To get the last character, you have to subtract 1 from length:
>>> last=word[length-1]
>>> print last
o
The alternative way is to use negative indices, which count backward from the end of the string. The expression word[-1] will give us the last letter which is o. Then word[-2] will give us the second to last letter and so on.
>>>print word[-1]
O
>>>print word[-2]
l 
>>>print word[-3]
L

Nema komentara:

Objavi komentar