【问题标题】:Python coding/ decoding cipherPython编码/解码密码
【发布时间】:2018-02-10 01:24:31
【问题描述】:

我正在尝试使用密码加密在 python 中对该函数进行编码然后解码。我写了这个函数。如何更改此功能以使其同时编码小写和大写字母?

def encrypt(message, key):
  alphabet="abcdefghijklmnopqrstuvwxyz"
  encMessage=""

  for character in message:
      if character in alphabet:
          index = alphabet.find(character)
          newPosition = (index+key)%26
          newCharacter = alphabet[newPosition]
          encMessage+=newCharacter
      else:
          encMessage+=character

  return encMessage

【问题讨论】:

  • 使用character.lower()获取字母的小写版本
  • (index+key)%26 不保证是字母数字字符,顺便说一句
  • @Barmar 在 for 循环中还是在 for 循环上方?
  • 怎么会在for循环之上呢? character 变量未在此处定义。
  • 这个函数真的是你写的吗?和this question一模一样

标签: python python-3.x caesar-cipher


【解决方案1】:

您可以使用大写字母来扩展字母表。您还需要更新模运算以获取您的newPosition。

def encrypt(message, key):

  # Extend your alphabet
  alphabet="abcdefghijklmnopqrstuvwxyz"
  alphabet += alphabet.upper()

  encMessage=""

  for character in message:
      if character in alphabet:
          index = alphabet.find(character)

          # Use the correct modulo
          newPosition = (index+key) % len(alphabet)

          newCharacter = alphabet[newPosition]
          encMessage+=newCharacter
      else:
          encMessage+=character

  return encMessage

【讨论】:

  • 您是否错过了另一个问题中的评论,他承认他有多个 SO 帐户并且他写了两个问题?
  • 我没有,我应该删除通知吗?你有什么建议,你似乎更清楚发生了什么。
  • 删除通知即可
  • 完成,感谢您为弄清楚这里发生了什么所做的工作。
猜你喜欢
  • 2021-04-15
  • 1970-01-01
  • 2019-03-09
  • 2019-12-19
  • 2012-04-10
  • 2012-06-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多