How to create a Caesar cipher function in Python?

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.