Python 在for循环中多次替换字母
我试图用for循环替换句子中的字符,更像是用giving cipherKey解密消息 我成功地将orgKey和cipherKey设置为相互对齐和替换。请参阅下面的代码,以清楚地了解这一点Python 在for循环中多次替换字母,python,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])
orgKey = [list]
cipherKey = [list]
message = "some secret message"
for i in range (len(orgKey)):
message = message.replace(cipherKey[i], orgKey[i])
print(message)
我本来希望有一条干净的消息,其中包含替换的字母,但由于message=message.replacecipherKey[I],orgKey[I]行包含在for循环中,因此它替换了orgKey长度中的每个字母。
使用这种方法最好、更干净的方法是什么?试试以下方法:
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)
仅当列表长度相同时。您可以使用lenmessage作为您的范围,即对于范围内的i lenmessage: