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

2024-05-26 00:33:42 发布

您现在位置: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 
      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


Tags: inputifshift字母chpgcaesarplaintext
2条回答

要解决间距问题,可以将else添加到if ch.isalpha(),只需将纯文本字符附加到密文中。这也将处理标点符号和其他特殊的非字母字符。你知道吗

要处理包装(例如X到A),您需要使用模运算符%。因为A是第65个ASCII字符,而不是第0个,所以您需要将alpha字符归零,然后应用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

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

代码

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

相关问题 更多 >