Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Caesar cipher ascii adding spaces

Tags:

python

ascii

I'm trying to make the Caesar cipher and I'm having a problem with it.

It works perfectly but I want to have spaces added to the word that is inputted. If you enter a sentence with spaces in it. It just prints out = instead of a space when it is Encrypted. Can anyone help me fix this so that it will print out spaces?

Here is my code:

word = input("What is the message you want to encrypt or decrypt :")
def circularShift(text, shift):
    text = text.upper()
    cipher = "Cipher = "
    for letter in text:
        shifted = ord(letter) + shift
        if shifted < 65:
            shifted += 26
        if shifted > 90:
            shifted -= 26
        cipher += chr(shifted)
        if text == (" "):
            print(" ")
    return cipher
print (word)
print ("The encoded and decoded message is:")
print ("")
print ("Encoded message  = ")
print (circularShift(word , 3))
print ("Decoded message  = ")
print (circularShift(word , -3))
print ("")
input('Press ENTER to exit')
like image 247
Kristen Sareen-Kadach Avatar asked May 10 '26 19:05

Kristen Sareen-Kadach


1 Answers

You need to take a close look at your conditions:

Given a space, ord(letter) + shift will store a 32+shift in shifted (35 when shift is 3). That is < 65, therefore 26 gets added, in this case leading to 61, and the character with number 61 happens to be =.

To fix this, make sure to only touch characters that are in string.ascii_letters, for example as the first statement in your loop:

import string

...
for letter in text:
    if letter not in string.ascii_letters:
        cipher += letter
        continue
...
like image 136
L3viathan Avatar answered May 13 '26 07:05

L3viathan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!