简体   繁体   中英

Trying to create a ROT13 decoder and I found an error I don't quite understand

I'm pretty new to the world of coding in general and after completing a recent Codecademy project themed about cryptography, I was inspired to try creating my own ROT13 decoder using a similar setup, since I've seen ROT13 used a lot on some fansites I've frequented to cover up spoilers. The code I wrote is as follows:

ABCs = "abcdefghijklmnopqrstuvwxyz"
punctuation = ".,?'! "
user_input = input("Enter message to be decoded: ")

def ROT13_decode(message):
    translation = ""
    for letter in message:
        if not letter in punctuation:
            letter_value = ABCs.find(letter)
            translation += ABCs[(letter_value + 13)]
        else:
            translation += letter
    return translation

print(ROT13_decode(user_input))

However, when debugging, I got the following error message:

line 10, in ROT13_decode
    translation += ABCs[(letter_value + 13)]
IndexError: string index out of range

I don't know how my string index can be out of range, when there's only 26 letters to work with. What am I missing?

When you add 13 to your letter value you have to be able to loop the result back to the beginning of the alphabet which is the entire trick that makes ROT13 work. If you change your translation code to:

translation += ABCs[(letter_value + 13) % 26]

The upper half of the alphabet which would normally give you a value that's bigger than the length of ABCs is guaranteed to always be less than 26.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM