1

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!

galaxies
  • 63
  • 7
  • You may be interested in [str.translate](https://docs.python.org/3/library/stdtypes.html#str.translate) and [str.maketrans](https://docs.python.org/3/library/stdtypes.html#str.maketrans). – Mark Tolonen Jan 13 '19 at 19:52

2 Answers2

2

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")
Paritosh Singh
  • 6,034
  • 2
  • 14
  • 33
0

Same as you do it with a space, you can do it with any character.

if char in string.punctuation+' ':
        encrypt = encrypt + char
Doron Sever
  • 65
  • 2
  • 2
  • 9