如何将用户输入转换为变量等效项?

时间:2016-11-04 11:24:14

标签: python

我正在制作编码和解码程序,现在我正在制作解码程序。我已将整个英文字母替换为另一个字母(例如a = e,b = f,c = g),并且我编写了代码,要求用户使用以下方式输入加密消息:

encrypted_message = input("Insert the encrypted message")

我希望这样做,以便用户可以输入"abc",python会将"abc"翻译成"efg"并输入。

2 个答案:

答案 0 :(得分:0)

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

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

答案 1 :(得分: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