Search code examples
pythonencryptioncaesar-cipher

How to leave punctuation unchanged in Caesar Cipher? - Python


I'm having trouble trying to leave the punctuation unchanged while encrypting or decrypting a message

# encryption
message = input("Enter a message to be encrypted: ") # user inputs message to be encrypted
offset = int(input ("Enter an offset: ")) # user inputs offset
print ("\t")

encrypt = " " 

for char in message:
    if char == " ":
        encrypt = encrypt + char
    elif char.isupper():
        encrypt = encrypt + chr((ord(char) + offset - 65) % 26 + 65) # for uppercase Z
    else:
        encrypt = encrypt + chr((ord(char) + offset - 97) % 26 + 97) # for lowercase z

print ("Your original message:",message)
print ("Your encrypted message:",encrypt)
print ("\t")

An example of what the output looks like if I try to encrypt a message with punctuation (offset of 8):

Your original message: Mr. and Mrs. Dursley, of number four Privet Drive, were proud to say that they were perfectly normal, thank you very much.
Your encrypted message:  Uzj ivl Uzaj Lczatmgh wn vcujmz nwcz Xzqdmb Lzqdmh emzm xzwcl bw aig bpib bpmg emzm xmznmkbtg vwzuith bpivs gwc dmzg uckp

I suspect this program is changing the punctuation to letters due to the chr(ord(char)) function.

Is there any way I can add in the actual punctuation to the encrypted message without changing the code too much? I would really appreciate any help, thank you!


Solution

  • You can get your desired result with just a one liner change by handling all non alpha characters in the first conditional using isalpha()

    # encryption
    message = input("Enter a message to be encrypted: ") # user inputs message to be encrypted
    offset = int(input ("Enter an offset: ")) # user inputs offset
    print ("\t")
    
    encrypt = " " 
    
    for char in message:
        if not char.isalpha(): #changed
            encrypt = encrypt + char
        elif char.isupper():
            encrypt = encrypt + chr((ord(char) + offset - 65) % 26 + 65) # for uppercase Z
        else:
            encrypt = encrypt + chr((ord(char) + offset - 97) % 26 + 97) # for lowercase z
    
    print ("Your original message:",message)
    print ("Your encrypted message:",encrypt)
    print ("\t")