Matthew Willis Matthew Willis - 1 month ago 9
Python Question

Python Caesar cipher decoding

I am new to Python and decided to make my own Caesar cipher encryptor. I've made the encrypter and it is ok, however, the decrypter can only successfully decrypt one word. If I enter a sentence, it merges the decryption all together. Is there an easy fix for this?

def decrypt():
ciphertext = raw_input('Please enter your Encrypted sentence here:')
shift = input('Please enter its shift value: ')
space = []

cipher_ords = [ord(x) for x in ciphertext]
plaintext_ords = [o - shift for o in cipher_ords]
plaintext_chars = [chr(i) for i in plaintext_ords]
plaintext = ''.join(plaintext_chars)
print 'Decryption Successful'
print ""
print 'Your encrypted sentence is:', plaintext

decrypt()

Answer

What I propose is to split your raw_input() at every space, iterate over each word in the split input, and then join the sentence back together with spaces. It seems to be the most canonical solution I could thin of:

def decrypt():
    ciphertext = raw_input('Please enter your Encrypted sentence here:')
    shift = int(raw_input('Please enter its shift value: '))
    space = []

    # creat a list of encrypted words.
    ciphertext = ciphertext.split()

    # creat a list to hold decrypted words.
    sentence = []

    for word in ciphertext:
        cipher_ords = [ord(x) for x in word]
        plaintext_ords = [o - shift for o in cipher_ords]
        plaintext_chars = [chr(i) for i in plaintext_ords]
        plaintext = ''.join(plaintext_chars)
        sentence.append(plaintext)

    # join each word in the sentence list back together by a space.
    sentence = ' '.join(sentence)
    print 'Decryption Successful\n'
    print 'Your encrypted sentence is:', sentence

decrypt()

Output:

Please enter your Encrypted sentence here: lipps xlivi
Please enter its shift value:  4
Decryption Successful

Your encrypted sentence is: hello there

Notes:

  • Never just do input() in Python 2.x because it uses eval() implicatedly. Which can be very dangers. Use int(raw_input()) instead.
  • I removed the extra print statement you had to create a new line. Append a new line to your second print statement instead.