另一种改进代码的方法

时间:2017-11-18 03:15:13

标签: python

谢谢大家对我之前提问的帮助。真的很有帮助!我的代码现在就是这个......

def intro():
    """This is the function that starts the program"""

    msg = input("Enter the message you wish to encrypt: ") # This ask the user to input a message to encrypt
    return msg


def shift(msg):
    """This function is the meat of the program. Shifting the message"""

    alpha = ['a', 'b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'] # Letters that the user can input
    rotate = int(input("The level of the encryption?: ")) #Tells how to shift letters, if message is "a" and inputs level 2, it becomes "c"
    text = "" #puts the tex between quotes
    for ch in msg:
        if ch == " " or ch == ".": 
            pass #If user inputs a blank or period it wont casue an error
        else:
            index = alpha.index(ch) # index becomes message and the ASCII
            newindex = (index + rotate) % len(alpha) #ASCII will shift by the rotate value and becomes newindex
            new= alpha[newindex]#new message becomes new
            text += new #the encrypted message is now text
    return text



def start():
    """Fuction that puts everything together and starts the program"""
    while True:
        msg = intro()
        if msg == '999':
            print("Farewell. We will see each other again soon, I guarantee it")
            break # If the user inputs "999" the program will end
       deep web shift(msg)
        print("Your encryptions is: " + text)#Output of the program

print("Hello there. Welcome to my deep web encryption services, Please press '999' if you wish to leave")#Tells the user what to do
print("Encryption level can be any numeric value")
start()

如果可能的话,这是我的另一个问题。我知道ascii的小写和大写是不同的。有没有办法可以换大写字母。喜欢,制作"你好"转移2来制作" Jgnnq"。如果用户输入无效的东西,它将保留它。一个例子是" hell @"转移2将成为" jgnn @"

1 个答案:

答案 0 :(得分:1)

str.maketransstr.translate围绕这些问题设计:将一组字符映射到另一组字符。

from string import ascii_lowercase, ascii_uppercase
from itertools import chain

alphabets = [ascii_lowercase, ascii_uppercase]

def shift(msg, rotate, alphabets):
    paired_letters = (zip(alphabet, alphabet[rotate:]+alphabet[:rotate]) for alphabet in alphabets)
    trans = str.maketrans(dict(chain.from_iterable(paired_letters)))
    return msg.translate(trans)

print(shift('helL@', 2, alphabets))

将打印

jgnN@