Python编码/解码密码

时间:2018-02-10 01:24:31

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

我正在尝试编码,然后使用密码加密在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

1 个答案:

答案 0 :(得分:0)

您可以使用大写字母扩展字母。您还需要更新模数操作以获取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