Hacking Secret Ciphers with Python

(Ann) #1
Chapter 17 – The Simple Substitution Cipher 245

Remember, our code in translateMessage() always replaces the character in charsA (the
top row) with the character at that same index in charsB (the middle row). So when lines 47 and
48 will swap the values in charsA and charsB, the code in translateMessage() will be
doing the decryption process instead of the encryption process.


simpleSubCipher.py
54. # loop through each symbol in the message
55. for symbol in message:
56. if symbol.upper() in charsA:
57. # encrypt/decrypt the symbol
58. symIndex = charsA.find(symbol.upper())


The for loop on line 55 will set the symbol variable to a character in the message string on
each iteration through the loop. If the uppercase form of this symbol exists in charsA
(remember that both the key and LETTERS only have uppercase characters in them), then we
will find the index of the uppercase form of symbol in charsA. This index will be stored in a
variable named symIndex.


We already know that the find() method will never return - 1 (remember, a - 1 from the
find() method means the argument could not be found the string) because the if statement on
line 56 guarantees that symbol.upper() will exist in charsA. Otherwise line 5 8 wouldn’t
have been executed in the first place.


The isupper() and islower() String Methods


The isupper() string method returns True if:



  1. The string has at least one uppercase letter.

  2. The string does not have any lowercase letters in it.


The islower() string method returns True if:



  1. The string has at least one lowercase letter.

  2. The string does not have any uppercase letters in it.


Non-letter characters in the string do not affect whether these methods return True or False.
Try typing the following into the interactive shell:





'HELLO'.isupper()
True




Free download pdf