user3832862
user3832862

Reputation: 31

Python 2 Caesar Cipher

My question is how to improve the code so that it can adapt to however long the input message is. As is, the message must be 5 letters. I would like to improve the code such that a message of any length can be inputted and the cipher will work with it. Help would be much appreciated. :-) See the code below!

#Enter your message
message=raw_input('Enter your message here. Make sure to use all CAPS througout your message and leave no spaces in between words.')
length=len(message)
print 'The length of your message is ',length

#This statement is a possible idea to let the program know how many letters it will be need to shift. But I don't know how to actually do this.
print chr(length+64)
#Indexes letters out of message.
A=message[length-length]
B=message[length-length+1]
C=message[length-length+2]
D=message[length-length+3]
E=message[length-length+4]

#Shifts letters and accounts for shifting XYZ to ABC. 
def shift(x):
    if ord(x)+3==91:
        return 65
    if ord(x)+3==92:
        return 66
    if ord(x)+3==93:
        return 67
    else:
        return ord(x)+3

a2=shift(A)
b2=shift(B)
c2=shift(C)
d2=shift(D)
e2=shift(E)


#Converts shifted ordinals back to characters
def convert(x):
    return chr(x)
first=convert(a2)
second=convert(b2)
third=convert(c2)
fourth=convert(d2)
fifth=convert(e2)

#Prints resultant characters
print first,second,third,fourth,fifth

Upvotes: 1

Views: 800

Answers (4)

Noctis Skytower
Noctis Skytower

Reputation: 21991

Here is a simple Caesar cipher program written for Python 3 that should not be very difficult to rewrite for Python 2:

import string

def main():
    key = 5
    table = str.maketrans(string.ascii_letters,
                          string.ascii_lowercase[key:] +
                          string.ascii_lowercase[:key] +
                          string.ascii_uppercase[key:] +
                          string.ascii_uppercase[:key])
    plaintext = input('Please enter a phrase: ')
    ciphertext = plaintext.translate(table)
    print('Your encrypted phrase is:', ciphertext)

if __name__ == '__main__':
    main()

Upvotes: 0

Roland Smith
Roland Smith

Reputation: 43495

The Ceasar cipher is built in in python 2;

In [6]: 'The Caesar cipher is built-in.'.encode('rot13')
Out[6]: 'Gur Pnrfne pvcure vf ohvyg-va.'

As you can see, this encoding only acts on letters, and it works for upper and lower case.

But is you want to remove spaces and make every thing upper-case, Python can do that as well;

In [9]: 'this is a string'.translate(None, ' \t')
Out[9]: 'thisisastring'

In [10]: 'this is a string'.translate(None, ' \t').upper()
Out[10]: 'THISISASTRING'

In [11]: 'this is a string'.translate(None, ' \t').upper().encode('rot13')
Out[11]: 'GUVFVFNFGEVAT'

Or in a different way;

In [15]: ''.join('this is a string'.split()).upper().encode('rot13')
Out[15]: 'GUVFVFNFGEVAT'

Upvotes: 1

Joran Beasley
Joran Beasley

Reputation: 113940

import string
shift_amt = 13
alphabet_lc = string.ascii_lowercase
shifted_lc = alphabet_lc[shift_amt:]+alphabet_lc[:shift_amt]

alphabet_uc = alphabet_lc.upper()  
shifted_uc = shifted_lc.upper()
trans_tab = string.maketrans(alphabet_lc+alphabet_uc,shifted_lc+shifted_uc)



message = "Encode Me To a new MessaGez!"
print message.translate(trans_tab)

is one way of doing it in Python2 at least

Upvotes: 2

ZenOfPython
ZenOfPython

Reputation: 901

Use two for loops, one for looping through each character, and one for shifting the character the desired amount of times. We use a function upper() to shift a character.

def upper(char):
    from string import ascii_letters as _all
    if char == ' ':
        return ' '
    return _all[_all.index(char)+1] if char != 'Z' else 'a'

def shift(message, key):
    temp = []
    for i in message:
        char = i
        for k in range(key):
            char = upper(char)
        temp.append(char)
    return ''.join(temp)

message=raw_input('Enter your message here: ')
key = int(raw_input('Enter the desired key: '))
length=len(message)
print 'The length of your message is', length

print 'Your encrypted message is {0}'.format(shift(message, key))

This runs as:

bash-3.2$ python caesar.py
Enter your message here: This works WITH or without CAPS
Enter the desired key: 10
The length of your message is 31
Your encrypted message is drsC GyBuC gSdR yB GsDryED MKZc
bash-3.2$ 

Upvotes: 1

Related Questions