Python Forum
len function - - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: len function - (/thread-14892.html)



len function - - jojotte - Dec-22-2018

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!


RE: len function - - ichabod801 - Dec-22-2018

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.


RE: len function - - jojotte - Dec-22-2018

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)



RE: len function - - ichabod801 - Dec-22-2018

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.


RE: len function - - jojotte - Dec-22-2018

OK, brilliant, makes sense!
Ta!


RE: len function - - buran - Dec-22-2018

If you don't know, python supports also negative indexes
name = input("provide an example of name:   ")
print(name[-1])