2016-11-07 98 views
0

我想知道如何輸入一個字符串並從字典中獲取多個密鑰?例如,這是我的代碼,我想打印「歡迎來到黑社會」,並用我的字典中的字母進行編碼。字典中的多個鍵?

def main(): 
    print("*********************************************************************************************") 
    print("What exactly is your use for this? Whatever, Enter a message because your hiding something...") 
    print("*********************************************************************************************") 

    userInput = input("Enter your message to encode: ") 
    userInput = userInput.lower() 
    # encoding dictionary 
    encoding = {"a":"b","b":"c","c":"d","d":"e","e":"f","f":"g","g":"h","h":"i","i":"j","j":"k","k":"l","l":"m","m":"n", 
       "n":"o","o":"p","p":"q","q":"r","r":"s","s":"t","t":"u","u":"v","v":"w","w":"x","x":"y", 
       "y":"z","z":"a"," ":"-"} 

    #userInput = encoding[key] 

    for key in encoding: 
     if (userInput == key): 
      print(encoding[key]) 
      break 

main() 
+0

爲了您的編碼做類似'CHR(ORD(「一」)+ 1)',而不是寫出來的字典 –

回答

0
print(''.join([encoding.get(letter, '') for letter in userInput])) 

基本上,你要通過輸入消息(userInput)以編碼整個事情循環。加入的參數([encoding.get(letter, '') for letter in userInput])的確如此:對於輸入中的每個字符,它都會找到匹配的編碼。.get也很方便,因爲在未找到字母的情況下(即用戶輸入了一個數字),該字符是空字符串。

''.join(something)something中的所有元素都作爲一個字符串放在一起。更一般地,'a string'.join(something)將在something的每個元素之間放置'a string',因此如果'a string'爲空,則將空字符串放在中間,以便將列表中的所有內容有效地連接到字符串中。

+0

你能解釋一下什麼在該行正在進行,如我是5? –

1

你不應該迭代encoding,它是字典。相反,您可以迭代輸入字符串,用encoding[character]替換每個character

''.join([encoding[c] for c in somestring])