I am doing a Python exercise where I have to write a program that randomly generates a password according to the following criteria:
It has to be formed from two randomly chosen words, taken from a huge text file with one word on each line.
Each word must have at least 3 letters and the password must be either 8, 9, or 10 letters in total.
The words are concatenated (with no space) and the first letter of each is capitalised.
My code is below:
# Randomly generate a two-word password from a text file of words, subject to various conditions
from sys import exit
from random import choice
print()
try:
inf=open("words.txt","r")
except FileNotFoundError:
print("Error: words.txt not found.")
print("Quitting...")
exit()
words=inf.readlines()
for word in words:
word=word.rstrip()
word=word.lower()
first=choice(words)
words.remove(first)
second=choice(words)
while len(first)<=2 or len(second)<=2 or len(first)+len(second) not in [8,9,10]:
first=choice(words)
words.remove(first)
second=choice(words)
first=first[0].upper()+first[1:]
second=second[0].upper()+second[1:]
password=first+second
print(password)
Whilst attempting this exercise, I observed that the each of the words in the password seem to have one extra space at the end, and that this is the 'end-of-line' character \n. However, I have included the line word=word.rstrip() and have read that this should remove all spaces, tabs and end-of-line characters. Yet the variables first and second both still have '\n' at the end even though they are randomly chosen from the list words, with .rstrip() applied. What is going on here? I'm sure I've
missed something.
The issue is that you are modifying the variable
wordbut not the listwordswithin the loop i quoted above A simple solution in my opinion would be to do a list comprehensionwords = [word.rstrip().lower() for word in words]This way your new list would be stripped without any whitespace