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 use the string slicing feature.

For instance, we write

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

to define the caesar function that takes the plaintext string and the number of positions to shift the characters in plaintext.

In it, we get the lowercase alpgabets in a string with

alphabet = string.ascii_lowercase

Then we shift the alphabet with

shifted_alphabet = alphabet[shift:] + alphabet[:shift]

Then we call maketrans to create a dict that maps the letters in alphabet to the letters in shifted_alphabet.

And then we call plaintext.translate with table to return a new string that maps the letters in the keys of table to the corresponding letter value.

Conclusion

To create a Caesar Cipher function in Python, we can use the string slicing feature.

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 *