82 http://inventwithpython.com/hacking
Email questions to the author: [email protected]
The string you pass as an argument to find() can be more than one character. The integer that
find() returns will be the index of the first character where the argument is found. Try typing
the following into the interactive shell:
'hello'.find('ello')
1
'hello'.find('lo')
3
'hello hello'.find('e')
1
The find() string method is like a more specific version of using the in operator. It not only
tells you if a string exists in another string, but also tells you where.
Practice Exercises, Chapter 6, Set C
Practice exercises can be found at http://invpy.com/hackingpractice6C.
Back to the Code
Now that we understand how if, elif, else statements, the in operator, and the find()
string method works, it will be easier to understand how the rest of the Caesar cipher program
works.
caesarCipher.py
- if symbol in LETTERS:
get the encrypted (or decrypted) number for this symbol
- num = LETTERS.find(symbol) # get the number of the symbol
If the string in symbol (which the for statement has set to be only a single character) is a
capital letter, then the condition symbol in LETTERS will be True. (Remember that on line
22 we converted message to an uppercase version with message = message.upper(), so
symbol cannot possibly be a lowercase letter.) The only time the condition is False is if
symbol is something like a punctuation mark or number string value, such as '?' or '4'.
We want to check if symbol is an uppercase letter because our program will only encrypt (or
decrypt) uppercase letters. Any other character will be added to the translated string without
being encrypted (or decrypted).