我想在python中加密字符串。 char中的每个字符都映射到密钥中的其他字符。例如,'a'
映射到'D'
,' b'映射到'd'
,'c'
映射到'1'
,依此类推,如下所示:
char = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
secretkey="Dd18Abz2EqNPWhYTOjBvtVlpXaH6msFUICg4o0KZwJeryQx3f9kSinRu5L7cGM"
如果我选择字符串"Lets meet at the usual place at 9 am"
,则输出必须为"oABjMWAABMDBMB2AMvjvDPMYPD1AMDBMGMDW"
答案 0 :(得分:3)
至于替换字符串中的多个字符
您可以使用str.maketrans
和str.translate
:
>>> char = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
>>> secretkey = "Dd18Abz2EqNPWhYTOjBvtVlpXaH6msFUICg4o0KZwJeryQx3f9kSinRu5L7cGM"
>>> trans = str.maketrans(char, secretkey)
>>> s = "Lets meet at the usual place at 9 am"
>>> s.translate(trans)
'0AvB WAAv Dv v2A tBtDP TPD1A Dv M DW'
或者如果您希望仅保留char
中的那些:
>>> ''.join(c for c in s if c in char).translate(trans)
'0AvBWAAvDvv2AtBtDPTPD1ADvMDW'
至于加密
我建议使用专用库,例如pycrypto。
答案 1 :(得分:0)
好的,我在这里做了两个假设。
L
应该映射到0
,而不是o
,对吗?那么代码就是:
to_encrypt = "Lets meet at the usual place at 9 am"
char = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
secretkey = "Dd18Abz2EqNPWhYTOjBvtVlpXaH6msFUICg4o0KZwJeryQx3f9kSinRu5L7cGM"
encrypted = ""
for c in to_encrypt:
if c in char:
encrypted += secretkey[char.index(c)]
print(encrypted)
输出结果为:
0AvBWAAvDvv2AtBtDPTPD1ADvMDW