Programming in Python; Writing a Caesar Cipher Using a Zip() Method [Duplicate]

I have a homework problem: to encrypt a message using a Caesar cipher. I need to be able to have the user input a number to shift the encryption by. For example, shifting by 4 would change 'A' into 'E'. The user also needs to input the string to be translated. The book says to use the zip() function to solve the problem. I'm not sure how that would work.

I have this (but it doesn't do anything):

def caesarCipher(string, shift):
    strings = ['abc', 'def']
    shifts = [2,3]
    for string, shift in zip(strings, shifts):
        # do something?

print caesarCipher('hello world', 1)
3

"zip" is a builtin function of Python, not a certain type of method as your question title implies.

>>> help(zip)
Help on built-in function zip in module __builtin__:

zip(...)
    zip(seq1 [, seq2 [...]]) -> [(seq1[0], seq2[0] ...), (...)]

    Return a list of tuples, where each tuple contains the i-th element
    from each of the argument sequences.  The returned list is truncated
    in length to the length of the shortest argument sequence.

>>> 
4

You can use zip() to build a lookup table (dictionary), and use the dictionary to encipher your text.

from string import ascii_lowercase as alphabet

def cipher(plaintext, shift):
   # Build a lookup table between the alphabet and the shifted alphabet.
   table = dict(zip(alphabet, alphabet[shift:] + alphabet[0:shift]))
   # Convert each character to its shifted equivalent. 
   # N.B. This doesn't handle non-alphabetic characters
   return ''.join(table[c] for c in plaintext.lower())
1
Marcus Vance

Marcus Vance

Cybersecurity & Digital Privacy Researcher

Marcus Vance is a cybersecurity auditor and technology writer dedicated to educating the public about online safety, data privacy regulations, enterprise security, and emerging cyber threats.

Share this article
Twitter Facebook Pinterest