Python Caesar CipherImplement a simple Caesar cipher with the maketrans and translate methods.
A Caesar cipher is primitive way to obscure text. In it, we shift letters in the alphabet a certain number of characters. Some ciphers substitute one alphabet for another one, with different ordering.Strings
The maketrans method makes a table that maps on character to another based on two character sets. This is ideal for the Caesar cipher. Here, we simply shift each character backwards four places.
So: We map the character "e" to "a" because "a" is four places before it. We wrap around for the first four letters to the last four.
Translate: The translate method applies the translation table to the input text. Our table supports no uppercase characters here.
Lower: We call lower() on the input, to normalize characters, before invoking translate.
Python program that uses Caesar cipher
# Create translation table.
trans = str.maketrans("abcdefghijklmnopqrstuvwxyz",
# Apply Caesar cipher.
# Characters must be lowercased.
It is possible to convert characters as you go along. And this approach could also apply a Caesar cipher. The maketrans method is faster in my testing—and you can dynamically construct tables.
Note: Maketrans accepts an input alphabet and an output one. So we can dynamically build those strings with logic.
And: We can then use translate as done in the example. A Caesar cipher needs no hard-coded values this way.
This kind of cipher
is not encryption. But it worth experimenting with ciphers when programming, particularly when learning. Understanding, and even breaking, ciphers can offer insights into a language's use.Caesar cipher: Wikipedia
You may not be a Roman Emperor, but you can still use ciphers. And with Python, and the maketrans method, you can do this with little extra code. Looping through and translating characters is often more confusing, prone to errors, slower.While
© 2007-2020 Sam Allen. Every person is special and unique. Send bug reports to email@example.com.