'How to replace every character in a string with another (using Python to decode a long monoalphabetic cipher)?

I have decoded a monoalphabetic cipher and I want to use Python to do all the replacement of characters for me since the message is pretty long. I tried using the .replace function inside a for loop but I can't figure out how to get it to work.

'''for i in Cipher_1:
  if i == 'A':
    i.replace('A','C')
  elif i == 'B':
    i.replace('B','I')
  elif i == 'C':
    i.replace('C','O')
  elif i == 'D':
    i.replace('D','V')
  elif i == 'E':
    i.replace('E','Y')
  elif i == 'F':
    i.replace('F','B')
  elif i == 'G':
    i.replace('G','L')
  elif i == 'H':
    i.replace('H','K')
  elif i == 'I':
    i.replace('I','F')
  elif i == 'J':
    i.replace('J','T')
  elif i == 'K':
    i.replace('K','Q')
  elif i == 'L':
    i.replace('L','M')
  elif i == 'M':
    i.replace('M','A')
  elif i == 'N':
    i.replace('N','D')
  elif i == 'O':
    i.replace('O','Z')
  elif i == 'P':
    i.replace('P','H')
  elif i == 'Q':
    i.replace('Q','P')
  elif i == 'R':
    i.replace('R','S')
  elif i == 'S':
    i.replace('S','#')
  elif i == 'T':
    i.replace('T','N')
  elif i == 'U':
    i.replace('U','U')
  elif i == 'V':
    i.replace('V','R')
  elif i == 'W':
    i.replace('W','G')
  elif i == 'X':
    i.replace('X','E')
  elif i == 'Y':
    i.replace('Y','W')
  elif i == 'Z':
    i.replace('Z','%')
print(Cipher_1)   '''

Any ideas?



Solution 1:[1]

You can use python's translate function to map each character to a new character. And then use this translation table to translate your string. Try this code:

Cipher_1 = "ABFDSDFSFDS"
alphabets = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
translation = "CIOVYBLKFTQMADZHPS#NURGEW%"
mytable = Cipher_1.maketrans(alphabets, translation)
translated_cipher = Cipher_1.translate(mytable)
print(Cipher_1) # ABFDSDFSFDS
print(translated_cipher) # CIBV#VB#BV#

Documentation: https://docs.python.org/3/library/stdtypes.html#str.maketrans

Solution 2:[2]

FULL DISCLOSURE: This is not secure encryption; this is merely a cryptogram puzzle generator. = )

Nonetheless, as RufusVS suggested, the maketrans and translate methods within the builtin str module should work well:

import string


text_to_encrypt = 'SCRAMBLE THIS MESSAGE'

k = string.ascii_uppercase
v = 'CIOVYBLKFTQMADZHPS#NURGEW%'

translate_table = text_to_encrypt.maketrans(k, v)

print(' Original Message:', text_to_encrypt)
print('Encrypted Message:', text_to_encrypt.translate(translate_table))

We first build a translation table, and then we apply that table to the message.

The ascii_uppercase constant within the string module isn't necessarily required; I simply used it for convenience.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 iR0ckY
Solution 2 Matt Turner