2017-11-08 3 views
4

시저 암호를 만들려고하는데 문제가 있습니다.Python Caesar 암호 ascii 공백 추가

완벽하게 작동하지만 입력 한 단어에 공백을 추가하고 싶습니다. 공백이있는 문장을 입력하면 단지 암호화 된 경우 공백 대신에 =을 인쇄합니다. 누구든지 공간을 인쇄 할 수 있도록이 문제를 해결할 수 있습니까? 당신은 당신의 조건에 가까운 모습을 취할 필요

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') 

답변

5

: 여기

내 코드입니다

공간을 감안할 때, ord(letter) + shift 저장하는 32 개 이상의 shift에서 shifted (35 shift가 3). 즉, < 65이므로이 경우 26이 추가되고 61로 이어지고 숫자 61 인 문자는 =이됩니다.

것은이 문제를 해결하려면 해당 루프에서 첫 번째 문으로, 예를 들어, string.ascii_letters에있는 문자를 터치해야합니다 :

import string 

... 
for letter in text: 
    if letter not in string.ascii_letters: 
     cipher += letter 
     continue 
... 
+0

나는 거기에 있었는지 몰랐던'string.ascii_letters'을 좋아한다 : D – Netwave

2

그냥 split 내용 : 여기

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 ("") 

당신이 have a