Categories
Python Answers

How to create a Caesar cipher function in Python?

Spread the love

Sometimes, we want to create a Caesar cipher function in Python.

In this article, we’ll look at how to create a Caesar cipher function in Python.

How to create a Caesar cipher function in Python?

To create a Caesar cipher function in Python, we can create our own function to map the string characters to the new characters.

For instance, we write:

import string


def caesar(plaintext, shift):
    alphabet = string.ascii_lowercase
    shifted_alphabet = alphabet[shift:] + alphabet[:shift]
    table = str.maketrans(alphabet, shifted_alphabet)
    return plaintext.translate(table)


print(caesar('foobar', 2))

to define the caesar function that takes the plaintext to encrypt and the shift to specify the number of positions to shift each character in the character set.

We get all the ASCII alphabet characters with string.ascii_lowercase.

Then we shift the alphabet with alphabet[shift:] + alphabet[:shift].

Next, we map each character to the new characters with str.maketrans(alphabet, shifted_alphabet).

And then we return the encrypted string with plaintext.translate(table).

Therefore, the print output should be 'hqqdct' since we shifted each character 3 positions to the right in the alphabet table.

Conclusion

To create a Caesar cipher function in Python, we can create our own function to map the string characters to the new characters.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

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