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,597
  • 5
  • 34
  • 51
J Doe
  • 113
  • 2
  • 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
  • 5,936
  • 8
  • 37
  • 80
Daniel Trugman
  • 6,930
  • 17
  • 39
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
  • 66,333
  • 7
  • 57
  • 95