Roger Hylton Roger Hylton - 25 days ago 7
Python Question

Python - IndexError: string index out of range

My program is meant to generate a random password that's 5 characters long using the characters given below in the char variable. The issue is with the randint i believe and cannot figure out why.

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.")


I get this error after getting to the part where my program generates the additional passwords.

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

Answer
>>> 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.

Since your string has length 67, the largest index it can take is 66, but you are sometimes trying to get the index 67, hence the IndexError.

Also, the first character is obtained by index 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

Therefore you should use [randint(0, 66)].

Or better yet:

# 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)]

or use this function in both places:

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

and finally:

from random import choice

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