Python 密文转换为明文

  • 需求
    • 输入一串字符
    • 如果碰到小写或大写字母,进行转换,a——z,b——y,c——x,大写字母也是
    • 如果是其他字符,就按原样输出
  • 判断逻辑
    • 小写字母  cond_a_z
    • 大写字母  cond_A_Z
    • 既不是小写,也不是大写  else
  • 具体的判断,比如小写字母:(大写也类似)
    • offset_a  输入的字符跟a的距离,那么(倒退回来的那个跟z的距离 == 输入的字符跟a的距离),尤其可以得到,最终的那个字符的位置 offset_z
    • offset_z  最终转换的字符的ASCII码
    • char_transfer  通过chr,转换得到最终的字符
  • content_output = ''.join(text_output)    # 转换格式,如果直接输出text_output,会得到:['z', 'y', 'x', '_', '3', '4', '9', '=', '_', 'C', 'B', 'A'],而不是:zyx_349=_CBA
  • 代码如下
     1 #coding:utf-8
     2 #__author__ = 'Diva'
     3 # 测试案例 abc_349=_XYZ
     4 
     5 # var
     6 CHAR_a = ord('a')
     7 CHAR_z = ord('z')
     8 CHAR_A = ord('A')
     9 CHAR_Z = ord('Z')
    10 
    11 # func
    12 def fun(text_input):
    13     text_output = []
    14     if len(text_input) < 1:
    15         return False
    16 
    17     for k in range(len(text_input)):
    18         char = text_input[k]
    19         char_ascii = ord(char)
    20         cond_a_z = (char_ascii) >= CHAR_a and char_ascii <= CHAR_z  # 小写字母情况
    21         cond_A_Z = (char_ascii) >= CHAR_A and char_ascii <= CHAR_Z  # 大写字母情况
    22 
    23         if cond_a_z:
    24             offset_a = char_ascii - CHAR_a
    25             offset_z = CHAR_z - offset_a
    26             char_transfer = chr(offset_z)
    27             text_output.append(char_transfer)
    28         elif cond_A_Z:
    29             offset_A = char_ascii - CHAR_A
    30             offset_Z = CHAR_Z - offset_A
    31             char_transfer = chr(offset_Z)
    32             text_output.append(char_transfer)
    33         else:
    34             text_output.append(char)
    35         content_output = ''.join(text_output)    # 转换格式
    36 
    37     print('输入的密文是:' + str(text_input))      # 必须加str,将list转换为str,否则报错,+只能链接同类型
    38     print('转换得到的明文是:' + str(content_output))
    39 
    40 # main
    41 if __name__ == '__main__':
    42     cipher_text = raw_input('请输入你要转换的密文:')
    43     fun(cipher_text)
  • 测试结果
  •  

posted @ 2017-09-12 11:37  _七杀  阅读(1825)  评论(0编辑  收藏  举报