【问题标题】:Python Caesar cipher ascii adding spacesPython Caesar cipher ascii 添加空格
【发布时间】:2017-11-08 09:57:17
【问题描述】:

我正在尝试制作凯撒密码,但我遇到了问题。

它工作得很好,但我想在输入的单词中添加空格。如果你输入一个带有空格的句子。它只是在加密时打印出 = 而不是空格。谁能帮我解决这个问题,以便打印出空格?

这是我的代码:

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

【问题讨论】:

    标签: python ascii


    【解决方案1】:

    您需要仔细查看您的情况:

    给定一个空格,ord(letter) + shift 将在shifted 中存储一个 32+shift(当shift 为 3 时为 35)。即 =。

    要解决此问题,请确保仅触摸 string.ascii_letters 中的字符,例如作为循环中的第一条语句:

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

    【讨论】:

    • 我喜欢string.ascii_letters 我不知道那里有:D
    【解决方案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 ("")
    

    你有一个live example

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-13
      • 2021-06-09
      • 1970-01-01
      • 2021-12-29
      • 2016-01-06
      相关资源
      最近更新 更多