Python Forum

Full Version: len function -
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hey!

I am trying to do the following:
1/user inputs a name e.g. "John".
2/user gets returned with the last character of the string e.g. "n".

Where I am so far:


name = input("provide an example of name:   ")
indexOfName = len(name)
lastLetterofName = name[indexOfName]
print(lastLetterofName)
This does not work.
I get IndexError: string index out of range

However, this works (see line 3):
name = input("provide an example of name:   ")
indexOfName = len(name)
lastLetterofName = name[indexOfName - 1]
print(lastLetterofName)
Any idea what I got wrong?
Thanks!
Python is what is called 0-indexed. The index of the first item in a list or string is 0. Thus the index of the last item is len(list_or_str) - 1.
Thanks for this.
However when I specifically print indexOfName I get 4 if, say, the name I input is John...?

name = input("provide an example of name:   ")
indexOfName = len(name)
print(indexOfName)
lastLetterofName = name[indexOfName - 1]
print(lastLetterofName)
Right. indexOfName is the result of len(name), which is the number of items in the sequence (letters in the string). So that is 4, since there are four letters in John. The len function gives the length, not the index of the last character. Those, as you have seen, are two different things.
OK, brilliant, makes sense!
Ta!
If you don't know, python supports also negative indexes
name = input("provide an example of name:   ")
print(name[-1])