python实现移位加密和解密

yipeiwu_com6年前Python基础

本文实例为大家分享了python实现移位加密和解密的具体代码,供大家参考,具体内容如下

代码很简单,就不多做解释啦。主要思路是将字符串转为Ascii码,将大小写字母分别移位密钥表示的位数,然后转回字符串。需要注意的是,当秘钥大于26的时候,我使用循环将其不断减去26,直到密钥等效小于26为止。

def encrypt():
  temp = raw_input("Please input your sentence: ")
  key = int(raw_input("Please input your key: "))
  listA = map(ord,temp)
  lens = len(listA)
  for i in range(lens):
    a = listA[i]
    if 65 <= a <= 90:
      a += key
      while a > 90:
        a -= 26
    elif 97 <= a <= 122:
      a += key
      while a > 122:
        a -= 26
    listA[i] = a
  listA = map(chr,listA)
  listA = ''.join(listA)
  print listA


def unencrypt():
  temp = raw_input("Please input your sentence: ")
  key = int(raw_input("Please input your key: "))
  listA = map(ord, temp)
  lens = len(listA)

  for i in range(lens):
    a = listA[i]
    if 65 <= a <= 90:
      a -= key
      while a < 65:
        a += 26
    elif 97 <= a <= 122:
      a -= key
      while a < 97:
        a += 26
    listA[i] = a
  listA = map(chr, listA)
  listA = ''.join(listA)
  print listA


a = int(raw_input("input 0 to encrypt and 1 to unencrypt"))

if a == 0:
  encrypt()
elif a == 1:
  unencrypt()

效果

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Python实现判断字符串中包含某个字符的判断函数示例

Python实现判断字符串中包含某个字符的判断函数示例

本文实例讲述了Python实现判断字符串中包含某个字符的判断函数。分享给大家供大家参考,具体如下: #coding=utf8 #参数包含两个: #containVar:查找包含的字符...

Python读写txt文本文件的操作方法全解析

Python读写txt文本文件的操作方法全解析

一、文件的打开和创建 >>> f = open('/tmp/test.txt') >>> f.read() 'hello python!\nhel...

python中从str中提取元素到list以及将list转换为str的方法

在python中时常需要从字符串类型str中提取元素到一个数组list中,例如str是一个逗号隔开的姓名名单,需要将每个名字提取到一个元素为str型的list中。 如姓名列表str =...

Python循环实现n的全排列功能

描述: 输入一个大于0的整数n,输出1到n的全排列: 例如: n=3,输出[[3, 2, 1], [2, 3, 1], [2, 1, 3], [3, 1, 2], [1, 3, 2]...

详细介绍Python进度条tqdm的使用

详细介绍Python进度条tqdm的使用

前言 有时候在使用Python处理比较耗时操作的时候,为了便于观察处理进度,这时候就需要通过进度条将处理情况进行可视化展示,以便我们能够及时了解情况。这对于第三方库非常丰富的Python...