2016-11-04 73 views
-1

我正在制作一个编码和解码程序,现在我正在制作解码程序。我已经取代不同的字母在整个英文字母(例如A = E,B = F,C =克)和我写,对于用户要求输入使用加密的消息的代码:如何将用户输入转换为等效的变量?

encrypted_message = input("Insert the encrypted message") 

我想这样做,用户可以输入​​,python会将​​翻译成"efg"然后输入回来。

+1

http://stackoverflow.com/a/3269756/1513933 –

回答

0

使用字典和然后映射用户的输入到字典的get方法来检索每个值:

>>> d = {'a':'e', 'b':'f', 'c':'g'} 
>>> print(*map(d.get, 'cab'), sep='') 
gef 
0

使用translate()方法:

对于Python 2.x的

from string import maketrans 

encrypted = "abc"         # chars to be translated 
decrypted = "efg"         # their replacements 

trantab = maketrans(originals, encrypted)  # make translation table from them 

print encrypted_message.translate(trantab)  # Apply method translate() to user input 

对于Python 3.x

encrypted = "abc"         # chars to be translated 
decrypted = "efg"         # their replacements 

trantab = str.maketrans(encrypted, decrypted) # make translation table from them 

print(encrypted_message.translate(trantab)) # Apply method translate() to user input 
+0

的可能的复制,请考虑接受并给予好评这是对您有用的答案。 – MarianD