import string
""" The function takes in a string, makes all characters lowercase, and removes all punctuation including space.
This function should be called by encrypt before encryption. """
def preprocess(plaintext):
translator=str.maketrans('','',string.punctuation)
plaintext=plaintext.translate(translator).lower()
return plaintext.lower().replace(" ", "")
""" Given the character 'ch' and an integer k,
representing the number of positions to shift this character,
return the result of shifting 'ch' by 'k' positions"""
def shift(ch,k):
return chr(97+( ord(ch)-97+k)%26) # equivalent to chr(ord('a')+( ord(ch)-ord('a')+k)%26)
""" Encrypt with Cesar cipher """
def encrypt(plaintext,k):
ciphertext = ''
plaintext = preprocess(plaintext)
for letter in plaintext:
ciphertext += shift (letter, k)
return ciphertext
""" Decrypt with Cesar cipher """
def decrypt(ciphertext,k):
plaintext = ""
for letter in ciphertext:
plaintext += shift(letter, -k)
return plaintext