In this section, we will explain what a Caesar cipher is and how to implement it in Python. Then, we will consider other shift values, modular arithmetic, and ROT13.
A Caesar cipher is an ancient trick where you just move every letter forward three characters in the alphabet. Here is an example:
- Plaintext: ABCDEFGHIJKLMNOPQRSTUVWXYZ
- Ciphertext: DEFGHIJKLMNOPQRSTUVWXYZABC
So, HELLO becomes KHOOR.
To implement it, we're going to use the string.find() method. The interactive mode of Python is good for testing new methods, hence it's easy to create a string. You can make a very simple script to implement the Caesar cipher with a string named alpha for alphabet. You can then take input from the user, which is the plaintext method, then set a value, n, which equals the length of the string, and the string out is equal to an empty string. We then have a loop that goes through n repetitions, finding the character from string in and then finding the location of that character in the alpha string. It then prints out those three values so that we can make sure that the script is working correctly, then it adds 3 to loc (location) and puts the corresponding character in string out, and again prints out partial values so that we can see that the script is working correctly. At the end, we print our final output. Adding extra print statements is a very good way to begin your programming because you can detect mistakes.