Predictive Hacks

Caesar Cipher in Python

caesar cipher

Caesar Cipher is the most popular encryption technique where each letter in the original text is replaced by a letter according to the shifted alphabet. For example, with a left shift of 3, D would be replaced by A, E would become B, and so on.

Let’s say that we shift the alphabet by 3 positions on the left. Then we get:


So, the algorithm is simple. We should replace every letter from the original text with the corresponding shifted one by taking into consideration the upper and lower case. We leave as is the characters which are out of the alphabet, like spaces, punctuations etc.

Caesar Cipher Code

The Caesar Cipher will take as input the original text and the key and we return the encrypted text.

def caesar_cipher(raw_text, key):
    shifted_alphabet = alphabet[26-key:]+alphabet[0:(26-key)]
    cipher_text = ""

    for i in range(len(raw_text)):
        char = raw_text[i]
        idx = alphabet.find(char.upper())
        if idx == -1:
            cipher_text = cipher_text + char
        elif char.islower():
            cipher_text = cipher_text + shifted_alphabet[idx].lower()
            cipher_text = cipher_text + shifted_alphabet[idx] 


Let’s see what is the encrypted text of the “The quick brown fox jumps over the lazy dog!” by taking a key=3

plain_text = "The quick brown fox jumps over the lazy dog!"
'Qeb nrfzh yoltk clu grjmp lsbo qeb ixwv ald!'

Decrypt the Caesar Cipher

In order to decrypt the Caesar Cipher, we need to set as key the 26 minus the encrypted key which was 3 in our case.

'The quick brown fox jumps over the lazy dog!'

Voilà. We showed how we can encrypt and decrypt the Caesar Cipher using Python!

Share This Post

Share on facebook
Share on linkedin
Share on twitter
Share on email

Leave a Comment

Subscribe To Our Newsletter

Get updates and learn from the best

More To Explore


Image Captioning with HuggingFace

Image captioning with AI is a fascinating application of artificial intelligence (AI) that involves generating textual descriptions for images automatically.


Intro to Chatbots with HuggingFace

In this tutorial, we will show you how to use the Transformers library from HuggingFace to build chatbot pipelines. Let’s