2016-11-11 99 views
0

我的程序旨在使用char變量中下面給出的字符生成一個長度爲5個字符的隨機密碼。問題在於我相信的randint,並且不知道爲什麼。Python - IndexError:字符串索引超出範圍

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
>>> 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) 
+0

OP *應*使用動態值,而不是一組整數,但你沒看錯。 –

+0

@SterlingArcher完成。 –

0

沒有看到你的代碼兩件事情。

  1. 有沒有必要明確告訴chars = str()你有兩次聲明這個變量。
  2. 在第25行:把str()值以外的chars

chars += str("\"~<>.,?/:;}{[]+_=-)(*&^%$ £@!+§qwertyuiopasdfghjklzxcvbnm1234567890" [randint(1, 67)])

相關問題