# The ultimate Caesar Cipher (Python)

Updated 1 Tallied Votes 653 Views

Python's double ended queue module makes Caesar's cipher easy.

''' Caesar_Cipher1.py
Caesar Cipher encryption/decryption
using Python's double-ended queue rotation
tested with Python 3.4.1  by  vegaseat  13jan2015
'''

from collections import deque

def caesar_cipher(text, shift, decode=False):
# avoid these shifts
if shift == 32 or shift >= 95:
shift = 13
# change from encode to decode if decode=True
if decode:
shift = -shift
# give alpha 94 ASCII characters
alpha = "".join(chr(c) for c in range(32, 127))
dq = deque(alpha)
# shift/rotate the alphabet (dq in place)
dq.rotate(shift)
crypted = ""
for c in text:
if c in alpha:
# get the letter's index in alpha and apply to dq
index_alpha = alpha.index(c)
crypted += dq[index_alpha]
else:
crypted += c
return crypted

# testing ...
# shift key should be higher than 0 (try 1 to 94)
shift = 11

# test
print("shift = {}".format(shift))
text = "The quick brown fox jumped over the lazy dogs ..123!{}"
print("Original text:")
print(text)

encoded = caesar_cipher(text, shift)
print("Encoded text:")
print(encoded)

print("Decoded text:")
print(caesar_cipher(encoded, shift, decode=True))

''' result ...
shift = 11
Original text:
The quick brown fox jumped over the lazy dogs ..123!{}
Encoded text:
I]Ztfj^X`tWgdlct[dmt_jbeZYtdkZgti]ZtaVontYd\ht##&'(upr
Decoded text:
The quick brown fox jumped over the lazy dogs ..123!{}
'''
vegaseat 1,735

Modified code to avoid shift of 32 or shifts higher or equal to 95.
A shift of 32 changes a..z to A..Z.
A shift of 95 wraps around to the beginning of alpha.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.