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

You could write

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

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.