Reputation: 21
I want to encrypt a string in python. Every character in the char is mapped to some other character in the secret key. For example 'a'
is mapped to 'D'
, 'b' is mapped to 'd'
, 'c'
is mapped to '1'
and so forth as shown below:
char = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
secretkey="Dd18Abz2EqNPWhYTOjBvtVlpXaH6msFUICg4o0KZwJeryQx3f9kSinRu5L7cGM"
If I choose the string "Lets meet at the usual place at 9 am"
the output must be "oABjMWAABMDBMB2AMvjvDPMYPD1AMDBMGMDW"
Upvotes: 1
Views: 1868
Reputation: 86
As for replacing multiple characters in a string
You can use str.maketrans
and 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'
or if you prefer to preserve only those in char
:
>>> ''.join(c for c in s if c in char).translate(trans)
'0AvBWAAvDvv2AtBtDPTPD1ADvMDW'
As for encrypting
I would recommend using a dedicated library for that, such as pycrypto.
Upvotes: 3
Reputation: 1234
Ok, I am making two assumptions here.
L
should be mapped to 0
, not to o
, right?So then the code would be:
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)
The output would be:
0AvBWAAvDvv2AtBtDPTPD1ADvMDW
Upvotes: 0