2017-11-08 22 views
4

シーザー暗号を作ろうとしていて、問題があります。Python Caesar暗号アスキースペースを追加する

これは完全に機能しますが、入力された単語にスペースを追加します。あなたがスペースを含む文を入力した場合。それは単に暗号化されているときにスペースの代わりに=を表示します。誰も私がスペースを印刷するようにこれを修正するのを助けることができますか?あなたの条件に近い見てみる必要がある

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+ shiftshifted(35 shiftが3であります)。つまり、< 65なので、26が追加され、この場合は61になり、61の文字は=になります。

import string 

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

私はそこにあったのを知らない 'string.ascii_letters'が好きです:D – Netwave

2

だけsplitコンテンツ:あなたのループの最初のステートメントとして例えば、string.ascii_lettersにある唯一のタッチ文字を確認して、この問題を解決するには

ここ

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

あなたはありがとうございましたlive example