0

I saw someone getting an assignment to implement the Vigenere Cipher, so I decided, just for the frig of it, to implement the Caesar Cipher. The algorithm below, however, doesn't account for spaces and punctuation. How can I account for those without redoing the whole thing?

from random import choice
from string import ascii_lowercase

# for both encryption algorithms use negative offset to decrypt

def caesar_cipher(text, offset):
    '''encrypts text with offset provided by user'''
    text, key = text.casefold(), ascii_lowercase
    cipher = [key[(key.index(char) + offset) % 26] for char in text if char in key]
    return cipher


def caesar_cipher_rnd(text):
    '''generates and returns random offset'''
    offset = choice(-13, 13)
    text, key = text.casefold(), ascii_lowercase
    cipher = [key[(key.index(char) + offset) % 26] for char in text if char in key] 
    return cipher, offset

Edited by Mickey_2

2
Contributors
2
Replies
43
Views
1 Year
Discussion Span
Last Post by Mickey_2
1

You could write

cipher = [(key[(key.index(char) + offset) % 26] if char in key else char) for char in text]
0

Hi, Grib,

I've tested your solution and it works.

I've also replaced ascii_lowercase with ascii_letters and removed the casefold() function. It makes the algorithm less robust for encryption, but CC is just a toy anyway.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.