通过Python中的输入实现Ceaser密码函数

通过Python中的输入实现Ceaser密码函数,python,Python,我试图在Python中创建一个Ceaser密码函数,它根据您输入的内容来转换字母 plainText = input("Secret message: ") shift = int(input("Shift: ")) def caesar(plainText, shift): cipherText = "" for ch in plainText: if ch.isalpha(): stayInAlphabet = ord(ch) + shift i

我试图在Python中创建一个Ceaser密码函数,它根据您输入的内容来转换字母

plainText = input("Secret message: ")
shift = int(input("Shift: "))

def caesar(plainText, shift): 
  cipherText = ""
  for ch in plainText:
    if ch.isalpha():
      stayInAlphabet = ord(ch) + shift 
      if stayInAlphabet > ord('z'):
        stayInAlphabet -= 26
      finalLetter = chr(stayInAlphabet)
      cipherText += finalLetter
  print(cipherText)
  return cipherText

caesar(plainText, shift)

例如,如果我把“三月的IDES”作为我的消息,把1作为我的移位,当它打算输出“UIF JEFT PG NBSDI”时,它会输出“UIF JEFT PG NBSDI”。它不会保留空格,当它应该保持原样时,也会将感叹号之类的东西移回去。字母也应该换行,这意味着如果我把移位设为3,X应该回到A。

密码不能产生预期结果的原因是您的代码没有考虑到它不是字母非数字字母的情况。因此,一个潜在的解决方案就是增加对空间的处理

代码

plainText = input("Secret message: ")
shift = int(input("Shift: "))


def caesar(plainText, shift):
    cipherText = ""
    for ch in plainText:
        if ch.isalpha():
            stayInAlphabet = ord(ch) + shift
            if stayInAlphabet > ord('z'):
                stayInAlphabet -= 26
            finalLetter = chr(stayInAlphabet)
            cipherText += finalLetter
        elif ch is " ":
            cipherText += " "
    print(cipherText)
    return cipherText


caesar(plainText, shift)
Secret message: THE IDES OF MARCH
Shift: 1
UIF JEFT PG NBSDI
示例

plainText = input("Secret message: ")
shift = int(input("Shift: "))


def caesar(plainText, shift):
    cipherText = ""
    for ch in plainText:
        if ch.isalpha():
            stayInAlphabet = ord(ch) + shift
            if stayInAlphabet > ord('z'):
                stayInAlphabet -= 26
            finalLetter = chr(stayInAlphabet)
            cipherText += finalLetter
        elif ch is " ":
            cipherText += " "
    print(cipherText)
    return cipherText


caesar(plainText, shift)
Secret message: THE IDES OF MARCH
Shift: 1
UIF JEFT PG NBSDI

要解决间距问题,您可以将
else
添加到
if ch.isalpha()
中,然后将纯文本字符附加到密码文本中。这还将处理标点符号和其他特殊的非字母字符

要处理包装(例如X到A),您需要使用模运算符
%
。因为
A
是第65个ASCII字符,而不是第0个,所以需要将字母字符的基数归零,然后应用mod,然后加回“A”的偏移量。要使用环绕移位,可以执行以下操作:
final_letter=chr((ord(ch)+shift-ord('A'))%26+ord('A'))
。注意26来自拉丁字母表中的字母数

考虑到这些,下面是一个完整的示例:

plain_text = input("Secret message: ")
shift = int(input("Shift: "))

def caesar(plain_text, shift): 
  cipher_text = ""
  for ch in plain_text:
    if ch.isalpha():
      final_letter = chr((ord(ch) + shift - ord('A')) % 26 + ord('A'))
      cipher_text += final_letter
    else:
      cipher_text += ch
  print(cipher_text)
  return cipher_text

caesar(plain_text, shift)
样本输入:

plain_text = "THE IDES OF MARCH"
shift = 1

cipher_text = caesar(plain_text, shift)
print(cipher_text)
# UIF JEFT PG NBSDI