一个简单的消息解码器

时间:2013-03-22 18:27:32

标签: python python-2.7

我构建了一个简单的消息编码器和解码器。编码器将每个字母的值递减3.例如:A将被D替换,B将变为E.解码器执行相反的操作。 有没有办法用更少的代码编写解码器,就像我用编码器一样? 我试图这样做(我输入代码),但它不起作用。 有什么建议吗?

import string

shift = 3 # a shift of 3 letters. for example: A would become D, B would become E...

# encoding message
encode = raw_input("Enter message to encode: ")
print "The encoded message is:",
for i in encode:
    print int(ord(i))-shift, # convert characters to numbers

print
print

#decoding message
decode = raw_input("Enter message to decode: ")
message = ""
for numStr in string.split(decode):
    asciiNum = eval(numStr) # convert digits to a number
    message = message + chr(asciiNum+shift) # append character to message and add shift

print "The decoded message is:", message

"""
#decoding message
decode = raw_input("Enter message to decode: ")
decode = int(decode)

print chr(decode+shift) # only works for one number

# doesn't work
for i in range(decode):
    print chr(decode+shift),
"""

1 个答案:

答案 0 :(得分:0)

您可以使用列表推导或生成器表达式来缩短代码。

>>> message = 'HelloWorld'
>>> encoded = ''.join(chr(ord(letter) - 3) for letter in message)
>>> decoded = ''.join(chr(ord(letter) + 3) for letter in encoded)