Hacking Secret Ciphers with Python

(Ann) #1
Chapter 4 – Strings and Writing Programs 43




spam[2]
'l'





Notice that the expression spam[0] evaluates to the string value 'H', since H is the first
character in the string 'Hello'. Remember that indexes start at 0, not 1. This is why the H’s
index is 0 , not 1.


Figure 4-1. The string 'Hello' and its indexes.

Indexing can be used with a variable containing a string value or a string value by itself such as
'Zophie'. Type this into the interactive shell:





'Zophie'[2]
'p'





The expression 'Zophie'[2] evaluates to the string value 'p'. This 'p' string is just like
any other string value, and can be stored in a variable. Type the following into the interactive
shell:





eggs = 'Zopie'[ 2 ]
eggs
'p'





If you enter an index that is too large for the string, Python will display an “index out of range”
error message. There are only 5 characters in the string 'Hello'. If we try to use the index 10 ,
then Python will display an error saying that our index is “out of range”:





'Hello'[10]
Traceback (most recent call last):
File "", line 1, in
IndexError: string index out of range




Free download pdf