Gabriel Bogatu
Gabriel Bogatu

Reputation: 21

python replace multiple characters in a string

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

Answers (2)

130333
130333

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

Yanick Nedderhoff
Yanick Nedderhoff

Reputation: 1234

Ok, I am making two assumptions here.

  1. I think the output you expect is wrong, for instance L should be mapped to 0, not to o, right?
  2. I am assuming you want to ignore whitespace, since it is not included in your mapping.

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

Related Questions