1

I'm making a cipher where a text input is given and the output is the input but shifted along 2 in the alphabet for example "hi" is turned into "jk". I'm having problems wrapping the list around so that "y" can turn into "b" and so on. Plaintext is a set input. Key is 2

charset=["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"] # characters to be encrypted

def caesar_encrypt(plaintext,key):

    plaintext = plaintext.upper() # convert plaintext to upper case
    ciphertext = "" # initialise ciphertext as empty string

    for ch in plaintext:
        if ch == " ":
            pass
        else:
            index = charset.index(ch)
            newIndex = index + key
            shiftedCharacter = charset[newIndex]
            ciphertext += shiftedCharacter
            print(ciphertext)
    return ciphertext
coder
  • 12,832
  • 5
  • 39
  • 53
J Doe
  • 113
  • 3
  • 11

2 Answers2

2

Just change:

newIndex = index + key

To:

newIndex = (index + key) % len(charset)

This way, the values will wraparound gracefully

Modulo (%) documentation

thumbtackthief
  • 6,093
  • 10
  • 41
  • 87
Daniel Trugman
  • 8,186
  • 20
  • 41
0

To shift, you can try this:

import string

converter = {string.ascii_uppercase[i]:string.ascii_uppercase[i+2] for i in range(24)}
Ajax1234
  • 69,937
  • 8
  • 61
  • 102