Substitution Cipher in Python

In this tutorial I will tell you about substitution cipher and how you can cipher a string in Python.

Substitution Cipher in Python

Let’s assume you want to send a secret letter to a security agency, you will want to keep the contents of the letter discrete. Substitution cipher can be used for this purpose. I have taken a string, Str, holding a value of ‘Hello World’. Now I wish to replace the letter ‘H’ with ‘J’. I can do this by using the replace() function. It takes two arguments as input, the letter to be changed and the letter to be changed into.

Code :

Str = "Hello world"
Str = Str.replace("H", "J")
print(Str)

Output :

Jello World

I have taken a text file, sample.txt as input. The contents of the file is :

Hi this is CodeSpeedy Technologies Pvt Ltd

Now I want to cipher this text file by replacing each character with the 5th alphabet of the English dictionary from the character.

Code :

import string
dict = {}
for i in range(len(string.ascii_letters)):
    dict[string.ascii_letters[i]] = string.ascii_letters[i - 5] 
    
data = ""  
file = open("Output_text.txt", "w")

with open("sample.txt") as f:
    while True:
        c = f.read(1)
        if not c:
            print("End of file")
            break
        if c in dict:
            data = dict[c]
        else:
            data = c
        file.write(data)
file.close()

Thus you can cipher any text file or string in Python.

Leave a Reply

Your email address will not be published. Required fields are marked *