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

2024-06-09 16:40:32 发布

您现在位置:Python中文网/ 问答频道 /正文

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

encrypted_message = input("Insert the encrypted message")

我想让用户可以输入"abc",python将"abc"翻译成"efg",然后再输入回来。你知道吗


Tags: the代码用户程序消息messageinput字母
2条回答

使用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

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

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

相关问题 更多 >