Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
len function -
#1
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!
Reply
#2
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.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#3
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)
Reply
#4
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.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#5
OK, brilliant, makes sense!
Ta!
Reply
#6
If you don't know, python supports also negative indexes
name = input("provide an example of name:   ")
print(name[-1])
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020