我构建了一个简单的消息编码器和解码器。编码器将每个字母的值递减 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),
"""