在字母表中向前移动字符串?

时间:2014-10-25 11:59:16

标签: python

我被问到创建一个加密输入的程序是一个挑战。我已经考虑过创建一个程序但是如何做到这一点并没有多少。看起来它不应该太复杂,但我的课程中没有教过任何内容。我也读了这篇文章Get character position in alphabet,但没有太多运气!到目前为止我有这个:

import sys
import os
import time
import string
def Cryption():
    ####################
    encrypt = 'encrypt'
    decrypt = 'decrypt'
    ####################
    s = raw_input("Would you like to encrypt or decrypt? Enter your answer")
    if encrypt in s:
        print("Loading encryption sector...")
        time.sleep(2)
        enc = raw_input("Please input the string you would like to encrypt")
        print ("Your decrypted word is: " + enc)
    if decrypt in s:
        print("Loading decryption sector...")
        time.sleep(2)
        dec = raw_input("Please input the string you would like to decrypt")
    else:
        print("Your input was invalid, please re-enter your choice!")
        r = raw_input("Press enter to restart your program")
        Cryption()
Cryption()

我在考虑是否将输入添加5添加到每个字母值上然后重新打印产品。我将使用哪些函数将5添加到字母表中的订单上? ORD()?如果是这样,有人会指出我如何使用它的方向?提前谢谢!

1 个答案:

答案 0 :(得分:0)

import string


def encrypt_s(shift):
    lower = string.ascii_lowercase
    # shift forward current index of each character + the shift
    dict_map = {k:lower[(lower.index(k)+shift)%26] for k in lower}
    return dict_map

def decrypt_s(shift):
    lower = string.ascii_lowercase
    # shift forward current index of each character - the shift to get original string
    dict_map = {k:lower[(lower.index(k)-shift)%26] for k in lower}
    return dict_map


def Cryption():

    ####################
    encrypt = 'encrypt'
    decrypt = 'decrypt'
    ####################
    s = raw_input("Would you like to encrypt or decrypt? Enter your answer")
    if encrypt in s:
        print("Loading encryption sector...")
        time.sleep(2)
        enc = raw_input("Please input the string you would like to encrypt").lower()
        enc_s = encrypt_s(5)
        enc = "".join([enc_s[char] if char in enc_s else char for char in enc])
        print ("Your encrypted word is: ",enc)
    elif decrypt in s:
        print("Loading decryption sector...")
        time.sleep(2)
        dec = raw_input("Please input the string you would like to decrypt").lower()
        dec_s = decrypt_s(5)
        dec = "".join([dec_s[char] if char in dec_s else char for char in dec])
        print ("Your decrypted word is: ",dec)
    else:
        print("Your input was invalid, please re-enter your choice!")