获取错误'字符串索引超出范围'

时间:2013-09-08 14:12:05

标签: python

我是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

1 个答案:

答案 0 :(得分: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)

现在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,len(LETTERS) 排除 ,这是LETTERS索引所允许的确切值。