Python caesar密码移位
我一直在尝试创建一个带有信息“我的秘密”和键6的凯撒密码程序-所有字母在密码字母表中向右移动6个位置,当字母从末端脱落时,字母“环绕”。使用密码,消息“我的秘密”将被编码为“gsumzxlzn”。但是,我保留了错误的编码和解码结果。结果是: 编码:sdfykixkz 解码:abcdefghi 请帮忙Python caesar密码移位,python,caesar-cipher,Python,Caesar Cipher,我一直在尝试创建一个带有信息“我的秘密”和键6的凯撒密码程序-所有字母在密码字母表中向右移动6个位置,当字母从末端脱落时,字母“环绕”。使用密码,消息“我的秘密”将被编码为“gsumzxlzn”。但是,我保留了错误的编码和解码结果。结果是: 编码:sdfykixkz 解码:abcdefghi 请帮忙 import sys ALPHABET= ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','
import sys
ALPHABET= ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z',' ']
def main(plaintext, key):
cypher = generate_cypher(key)
plaintext = sys.argv[1]
e_code = encode_message(plaintext, cypher)
mes s= decode_message(e_code, cypher)
def generate_cypher(key):
cipher = []
for i in range(len(ALPHABET)):
cipher.append(ALPHABET[i+key%27])
print(cipher)
return(cipher)
def encode_message(plaintext,cipher):
key = int(sys.argv[2])
en_code=''
for c in plaintext:
if c in cipher:
en_code+=cipher[(cipher.index(c)+key)%(len(cipher))]
print("Encoded: ", en_code)
return en_code
def decode_message(e_code,cipher):
key = int(sys.argv[2])
message = []
for i in range(len(e_code)):
message.append(cipher[i-key%27])
mess=''.join(message)
print("Decoded: ", mess)
return mess
i+键%27
和i-键%27
的可能重复项看起来可疑,请注意模运算符%
比+
更强(先执行)。可以使用括号指定执行顺序。也要养成使用空格运算符的习惯,例如,为了可读性,它应该读取例如i+键%27
。谢谢你的建议,但我认为user1063450的问题不适用于我的问题,因为键依赖于字符串的索引进行编码。使用ord()函数将字符串转换为数字可能更容易,移动数字,然后使用chr()将数字转换回字符串。