Matthew Brzezinski
Matthew Brzezinski

Reputation: 1794

String Index Out Of Range, Vigenere Cipher

I'm working on implementing a Vigenere Cipher. I'm getting the error:

IndexError: string out of range

import sys

# Get the message and key 
message = (sys.argv[1]).lower()
key = (sys.argv[2]).lower()

# Open file
f = open('Cipher.txt', 'w')

for i in range(len(message)):
    if i > len(key):
        j = i % len(key)
        f.write(str(ord(message[i]) + ord(key[j]) % 26 + ord('a')))
    else:
        f.write(str(ord(message[i]) + ord(key[i]) % 26 + ord('a')))
f.close()

I'm getting it on the line after f.write(str(ord(message[i]) + ord(key[i]) % 26 + ord('a'))). I understand that my key may be shorter than the length of message that's why I put a check in front of it. For example if my key is test and I've gotten to the 5th character I'll come full circle back to the t in test.

Upvotes: 1

Views: 93

Answers (1)

Jed Fox
Jed Fox

Reputation: 3025

If i == len(key), the value returned will be i.

Replace

    if i > len(key):
        j = i % len(key)
        f.write(str(ord(message[i]) + ord(key[j]) % 26 + ord('a')))
    else:
        f.write(str(ord(message[i]) + ord(key[i]) % 26 + ord('a')))

With:

a = ord('a')
  ...
    j = i % (len(key) - 1)
    f.write(str((ord(message[i])-a + ord(key[j])-a) % 26 + a))

Upvotes: 1

Related Questions