在for循环中多次替换字母的

2024-09-29 01:27:22 发布

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

我正在尝试使用for循环(更像是解密消息)替换句子中的字符,并使用giving cipherKey

我成功地将orgKey和cipherKey设置为相互对齐和替换(请参阅下面的代码以获得对此的清晰理解)

orgKey = [list]
cipherKey = [list]
message = "some secret message"

for i in range (len(orgKey)):
    message = message.replace(cipherKey[i], orgKey[i])
    print(message)

我本来希望有一个干净的消息,其中包含替换的字母,但是由于for循环中包含了"message = message.replace(cipherKey[i], orgKey[i])行,因此它替换了长度为orgKey的每个字母。 用这种方法最好、更干净的方法是什么


Tags: 方法代码消息messagefor字母请参阅some
1条回答
网友
1楼 · 发布于 2024-09-29 01:27:22

试试这个:

orgKey = [list]
cipherKey = [list]
message = "some secret message"

message_encrypt = ''
dictionary = dict(zip(orgKey, cipherKey))
for char in message:
    message_encrypt += dictionary.get(char,' ')
print(message_encrypt)

只有在列表长度相同的情况下

相关问题 更多 >