2017-11-18 6 views
0

私の以前の質問で助けをいただき、ありがとうございます。本当に助けになりました!私のコードは今これです...コードを改善する別の方法

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が異なることを知っています。大文字をシフトする方法はありますか? 「Jgnnq」を作成するために「Hello」シフトを2つ作成します。また、ユーザーが無効なものを入力すると、それを保持します。 "hell @"が2だけシフトする例は、 "jgnn @"になります。

+3

あなたでしたupvoteしないかを印刷したり、あなたの前の質問への答えを受け付けます - これはhttps://stackoverflow.com/help/someone-answers見るには –

+0

この問題は、に最適と思われます['str.maketrans'](https://docs.python.org/3/library/stdtypes.html#str.maketrans)と' str.translate' –

答えて

1

str.maketransおよびstr.translateは、1つの文字セットを別の文字セットにマッピングするように設計されています。

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('[email protected]', 2, alphabets)) 

[email protected]