caesar cipher python中的简单加密代码

时间:2012-01-12 04:55:09

标签: python

  

可能重复:
  Caesar's Cipher using python, could use a little help

def affine (a, b):
    for i in range(26):
        print chr(i+65) + ": " + chr (((a*i+b)%26)+65)

这是我遇到的事情。我如何使用这个消息" Hello world"并加密它?

还有如何解密消息?

1 个答案:

答案 0 :(得分:0)

这是一种可读但非常简单的方式:

   def encript(message, offset):
       result = ""
       for letter in message:
           if letter.isalpha():
               new_letter = chr(ord(letter) + offset)
               if (new_letter > "Z" and letter.isupper()) or (new_letter > "z" and letter.islower()):
                    new_letter = chr(ord(new_letter) - 26)
           else:
               new_letter = letter
           result += new_letter
        return result

因此可以编写单行版本:

>>> encript = lambda x, offset: "".join(chr(ord(le) + ((offset - (26 if (ord(le.upper()) + offset > ord("Z") )  else 0 ) ) if le.isalpha() else 0))  for le in x )
>>> encript("IBM 9000", -1)
'HAL 9000'