How do I Use String Indexes?


#1

URL… https://www.codecademy.com/courses/learn-python/lessons/strings--console-output/exercises/access-by-index?action=resume_content_item&link_content_target=interstitial_undefined

CODE… fifth_letter = “Y”
" MONTY " “[Y]”
print fifth_letter

Error Message; Remember to use the access operator [] to get the character “Y”.

This is what I get after running the code. however when I use the operator [] like this

fifth_letter = “[Y]”
" MONTY " “[Y]”
print fifth_letter

Error Message is… The value of fifth_letter is “[Y]” instead of “Y”.


FAQ: Learn Python – Strings & Console Output – Access by Index
FAQ: Learn Python – Strings & Console Output – Access by Index
#2

we can get a value from a string using index, for example:

print "hello world"[0]

would print h, given that is the letter at index. using [1] instead of [0] would give e, given that is the second letter positioned at index 1

this is also what you need to do in this exercise


#3

Now, this is my code and though it does print Y

fifth_letter = " MONTY " [5]
" MONTY "
print fifth_letter

yet I am still getting this

error message…Remember to use the access operator [] to get the character “Y”.


#4

indexes are zero indexed based, while we humans start counting at one. So the 5th letter is what index?


#5

When you start counting from 0 there will be no 5th letter… May I ask why the computer is still able to print Y?


#6

Yes, but if i say the 5th letter i start counting at 1, which does exist. If i said the 5th index, that does indeed not exist when string is monty

there is a difference between 5th letter/element and 5th index.


#7

Think of it as translating. You have the real world numbers where you count 1, 2, 3, 4, 5 and then the editor translation as 0, 1, 2, 3, 4
With MONTY, the real world has the fifth letter as Y but in your Editor, you have to translate it to Python so the computer can understand. So to us, the 5th letter real world is equal to the 4th letter in Python language.
To make Python display Y, we have to use
fifth_letter = "MONTY’[4]
print fifth_letter
and then the computer will know to display Y.
The computers first number is always going to be zero in Python. In the real world, the concept of zero was not realized until after the values were created, so everyone counts at 1. Imho, we should count with zero to start, as in I have 0 apples and I go to the store to buy 3 apples. I went from having 0 apples to 3 apples. BUT it is redundant to us since we know that zero is a given.


#8