-1

我是 python 编程的新手,我遇到了这个奇怪的错误。

Traceback (most recent call last):
  File "C:/Documents and Settings/All Users/Documents/python/caeser hacker.py", line 27, in <module>
    translated = translated + LETTERS[num]
IndexError: string index out of range

有什么解决办法吗?

完整代码:

#caeser cipher hacker
#hhtp://inventwithpython.com/hacking {bsd licensed}

message='GUVF VF ZL FRPERG ZRFFNTR.'
LETTERS='ABCDEFGHIJKLMNOPQRSTUVWXYZ'

#loop through every possiable key
for key in range (len(LETTERS)):

    #it is important to set translated to blank string so that the
    #previous iteration's value for translated is cleared.
    translated=''

    #the rest of the program is the same as the caeser program.
for symbol in message:
    if symbol in LETTERS:
        #GET THE ENCRYPTED (OR DECRYPTED) NUMBER FOR THIS SYMBOL
        num= LETTERS.find(symbol) # get the number of the symbol
        num = num - key

        # handle the wrap-around if num is larger that the length of
        #LETTERS or less than 0
        if num >= 0:
           num = num +len(LETTERS)

        # add encrypted/decrypted numbers at the end of translad
        translated = translated + LETTERS[num]

    else:
         # just add the symbol without encrypting/decrypting
         translated = translated + symbol

#print the encrypted/decrypted string to the screen
print(translated)

# copy the encrypted /decrypted string to the clipboard
4

1 回答 1

2

这些行num很好地超出了允许的索引范围:

# handle the wrap-around if num is larger that the length of
#LETTERS or less than 0
if num >= 0:
   num = num +len(LETTERS)

Now保证num等于或大于,这是一个无效的索引。len(LETTERS)

也许您打算改用%模数?

# handle the wrap-around if num is larger that the length of
#LETTERS or less than 0
num %= len(LETTERS)

%模数运算符会将值限制在范围内([0, len(LETTERS))因此包含 0,排除0 ,这是允许索引len(LETTERS)到.LETTERS

于 2013-09-08T14:27:02.833 回答