HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonModerate

Caesar cipher in Python

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
caesarpythoncipher

Problem

I wrote this looping Caesar cipher with a default key. I'd love for some input on how I could make this operate better/more effectively.

#Et Tu, Brute? [Caesar's Cipher]
#loops?
#Determine type of cipher...
doLoop=("y")
while doLoop==("y"):
#yep. loops.    
    det=input("Enter N for number or C for character; 'exit' to quit program ").lower() #lower case for simplicity! it don't care!
#Now the fun part!
#Numbers...
    if (det)==("n"):
        print("The default cipher key is 5")
        numRaw=input("Enter number to be decoded: ")
        if ord(numRaw)<ord("5"):
            numDec=ord(numRaw)+5
        else:
            numDec=ord(numRaw)-5
        print("The decoded number is: ",(chr(numDec)))

#Letters...
    if (det)==("c"):
        print("The default cipher key is 13")
        charRaw=input("Enter character to be decoded: ").lower() #lower case for simplicity!
        if ord(charRaw)<ord("m"):
            charDec=ord(charRaw)+13
        else:
            charDec=ord(charRaw)-13
        print("The decoded character is: " , (chr(charDec)))
    if det==("exit"):
        break

Solution

Python strings have a translate method that applies a substitution cipher. There is also a function str.maketrans (string.maketrans in Python 2) that helps with building the translation table:

>>> from string import ascii_lowercase as alphabet
>>> shift = 13
>>> cipher = str.maketrans(alphabet, alphabet[shift:] + alphabet[:shift])
>>> print("caeser salad is tasty".translate(cipher))
pnrfre fnynq vf gnfgl


of coarse in python2(with a shift of 13) one can simply do "My Message".encode("rot13")

Code Snippets

>>> from string import ascii_lowercase as alphabet
>>> shift = 13
>>> cipher = str.maketrans(alphabet, alphabet[shift:] + alphabet[:shift])
>>> print("caeser salad is tasty".translate(cipher))
pnrfre fnynq vf gnfgl

Context

StackExchange Code Review Q#32694, answer score: 15

Revisions (0)

No revisions yet.