Saturday, 6 September 2014

Strings & Outputs: Indexing By Number

And we continue on from the previous post, we are now looking at Access by Index which is essentially that each character in a string is assigned a number. As such, the numbering system begins at 0 so for instance; PYTHON is 5 characters long in terms of numbers because P = 0 and so on.

As you can see below, the code is trying to get us to print the 5th letter.

or in print if you prefer:

"""
The string "PYTHON" has six characters,
numbered 0 to 5, as shown below:

+---+---+---+---+---+---+
| P | Y | T | H | O | N |
+---+---+---+---+---+---+
  0   1   2   3   4   5

So if you wanted "Y", you could just type
"PYTHON"[1] (always start counting from 0!)
"""
fifth_letter =

print fifth_letter

For this activity, CA is wanting me to use the fifth letter from MONTY
The fifth letter in MONTY is Y
For the code to run, we add "MONTY"[4]
The quotation marks go in too otherwise it doesn't come up however, we have a new addition of [4] which using pythons indexing means that 4 tells it to print the Y.

See below to understand a little better (It puzzled me for a little so don't worry if you get stuck too)


Or the code if you prefer:

fifth_letter = "MONTY"[4]

print fifth_letter

Thats all for this post!

No comments:

Post a Comment