Python - IndexError:字符串索引超出范围

时间:2016-11-11 20:54:51

标签: python python-3.x

我的程序是使用char变量中下面给出的字符生成一个长度为5个字符的随机密码。问题在于我相信兰丁,并且无法弄清楚原因。

from random import randint
print("1. 5 Letters")
enc = input("Please enter your desired option: ")
if enc == "1":
    chars = str()
    for i in range (1, 6+1):
        chars += str("\"~`<>.,?/:;}{[]+_=-)(*&^%$£@!±§qwertyuiopasdfghjklzxcvbnm1234567890qwertyuiopasdfghjklzxcvbnm1234567890" [randint(1, 67)])
    print("Your password is: " + chars)
    print("\n")

    yon = input("Do you want a new password (yes or no): ")
    if yon == "yes":

        np = int(input("How many new passwords do you want: "))
        print("\n")
        count = 0
        for i in range(1, np+1):
            count += 1
            chars = str() 
            for i in range (1, 6 + 1):
                chars += "\"~`<>.,?/:;}{[]+_=-)(*&^%$£@!±§qwertyuiopasdfghjklzxcvbnm1234567890" [randint(1, 67)]
            print("Your password is : " + str(chars) + "  This is password number: " + str(count) + "/" + str(np))
            print("\n")
    elif yon == "no":
        print("Goodbye.")

我到达程序生成附加密码的部分后出现此错误。

Traceback (most recent call last):
  File "/Users/rogerhylton/Desktop/Coding/Python/te.py", line 25, in <module>
    chars += "\"~`<>.,?/:;}{[]+_=-)(*&^%$£@!±§qwertyuiopasdfghjklzxcvbnm1234567890" [randint(1, 67)]
IndexError: string index out of range

2 个答案:

答案 0 :(得分:2)

>>> from random import randint
>>> randint(1, 3)
2
>>> randint(1, 3)
3
>>> help(randint)
Help on method randint in module random:

randint(a, b) method of random.Random instance
    Return random integer in range [a, b], including both end points.

由于您的字符串长度为67,因此它可以采用的最大索引是66,但您有时会尝试获取索引67,因此IndexError

此外,第一个字符是通过索引0获得的:

>>> "abc"[0]
'a'
>>> "abc"[1]
'b'
>>> "abc"[2]
'c'
>>> "abc"[3]
Traceback (most recent call last):
  File "<input>", line 1, in <module>
IndexError: string index out of range

因此,您应该使用[randint(0, 66)]

或者更好:

# Declare this variable once
possible_chars = "\"~`<>.,?/:;}{[]+_=-)(*&^%$£@!±§qwertyuiopasdfghjklzxcvbnm1234567890qwertyuiopasdfghjklzxcvbnm1234567890"

# Use this line in both places instead of duplicating the string literal
char = possible_chars[randint(0, len(possible_chars) - 1)]

或在两个地方使用此功能:

def get_random_char():
    possible_chars = "\"~`<>.,?/:;}{[]+_=-)(*&^%$£@!±§qwertyuiopasdfghjklzxcvbnm1234567890qwertyuiopasdfghjklzxcvbnm1234567890"
    return possible_chars[randint(0, len(possible_chars) - 1)]

最后:

from random import choice

def get_random_char():
    possible_chars = "\"~`<>.,?/:;}{[]+_=-)(*&^%$£@!±§qwertyuiopasdfghjklzxcvbnm1234567890qwertyuiopasdfghjklzxcvbnm1234567890"
    return choice(possible_chars)

答案 1 :(得分:0)

您的代码中有两件事。

  1. 没有必要明确告诉chars = str()你已经两次声明这个变量。
  2. 第25行:将str()置于chars的值之外,即
  3. chars += str("\"~<>.,?/:;}{[]+_=-)(*&^%$ £@!+§qwertyuiopasdfghjklzxcvbnm1234567890" [randint(1, 67)])