C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
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",
"wxyzabcdefghijklmnopqrstuv")
# Apply Caesar cipher.
print("exxegoexsrgi".translate(trans))
print("attackatonce".translate(trans))
# Characters must be lowercased.
print("EXXEGOexsrgi".lower().translate(trans))
Output
attackatonce
wppwygwpkjya
attackatonce
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.