Reputation: 95
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')
Upvotes: 3
Views: 1362
Reputation: 42678
Just split
the content:
print (word)
print ("The encoded and decoded message is:")
print ("")
print ("Encoded message = ")
encoded = " ".join(map(lambda x: circularShift(x, 3), word.split()))
print (encoded)
print ("Decoded message = ")
encoded = " ".join(map(lambda x: circularShift(x, -3), encoded.split()))
print (encoded)
print ("")
Here you have a live example
Upvotes: 2
Reputation: 27273
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
...
Upvotes: 5