By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
440,235 Members | 1,011 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 440,235 IT Pros & Developers. It's quick & easy.

How to get rid of a character from a password

P: 32
I made a random password generator for a project and it works fine, but when it generates passwords, it always adds " { " to a password or two. Why does it add this and how do I fix it?

Expand|Select|Wrap|Line Numbers
  1. import os
  2. import random
  3. from Tkinter import *
  4. from tkMessageBox import *
  5.  
  6. class Application(Frame):
  7.     def __init__(self, master=None):
  8.         Frame.__init__(self, master)
  9.         self.grid()
  10.         self._passwordLength = StringVar()
  11.         self._passwordLength.set("")
  12.         self._passwordAmount = StringVar()   # create a String control variable
  13.         self._passwordAmount.set("")
  14.         self._fileName = StringVar()
  15.         self._fileName.set("")
  16.         top = self.winfo_toplevel()  # find top-level window
  17.         top.title("Random Password Generator")
  18.         self._createWidgets()
  19.  
  20.     def _createWidgets(self):
  21.         siteLabel = Label(self, text="Password Lengths Wanted:", anchor = E, width = 20)
  22.         siteLabel.grid(row = 0, column = 0)
  23.         siteLabel = Label(self, text="Password Amount Wanted:", anchor = E, width = 20)
  24.         siteLabel.grid(row = 1, column = 0)
  25.         siteLabel = Label(self, text="File Name:", anchor = E, width = 20)
  26.         siteLabel.grid(row = 2, column = 0)
  27.         lengthEntry = Entry(self, takefocus = 1,
  28.                           textvariable = self._passwordLength)
  29.         lengthEntry.grid(row = 0, column = 1, sticky=E+W)
  30.         amountEntry = Entry(self, takefocus = 1,
  31.                           textvariable = self._passwordAmount)
  32.         amountEntry.grid(row = 1, column = 1, sticky=E+W)
  33.         fileEntry = Entry(self, takefocus = 1,
  34.                           textvariable = self._fileName)
  35.         fileEntry.grid(row = 2, column = 1, sticky=E+W)
  36.         self._button = Button(self, text = "Generate", command = self._getData, width = 20)
  37.         self._button.grid(row = 3, column = 0)
  38.         self._button = Button(self, text = "Quit", command = self._quitProgram, width = 20)
  39.         self._button.grid(row = 3, column = 1)
  40.  
  41.     def _getData(self):
  42.         try:
  43.             passwordLength = int(self._passwordLength.get())
  44.             passwordAmount = int(self._passwordAmount.get())
  45.         except:
  46.             showwarning("Error","Please check you input.")
  47.         self._generatePasswords(passwordLength, passwordAmount)
  48.  
  49.     def _generatePasswords(self, passwordLength, passwordAmount):
  50.         fileName = str(self._fileName.get())
  51.         if ".txt" not in fileName:
  52.             fileName += ".txt"
  53.         if os.path.isfile(fileName):
  54.             if askyesno("Verify", "This file already exists, would you like to overwrite it?"):
  55.                 fileToWrite = open(fileName, "w")
  56.         else:
  57.             fileToWrite = open(fileName, "w")
  58.         try:
  59.             randomize(passwordLength, passwordAmount, fileToWrite)
  60.             if True:
  61.                 showwarning("Random Password Generator", "Passwords Created! Check your folder!")
  62.         except:
  63.             showwarning("Error"," Please check your input.")
  64.  
  65.     def _quitProgram(self):
  66.         if askyesno('Verify', 'Are you sure you would like to quit the program?'):
  67.             root.destroy()
  68.  
  69. # end class Application
  70.  
  71. def main():
  72.     Application().mainloop()
  73.  
  74. def randomize(length, amount, fileToWrite):
  75.     for num in xrange(amount):
  76.         newPassword = ""
  77.         for count in xrange(length):
  78.             randomInt = random.randint(0,26)
  79.             newPassword += chr(randomInt+97)
  80.             count += 1
  81.         fileToWrite.write(newPassword+"\n")
  82.     fileToWrite.close()
  83.  
  84. root = Tk()
  85. main()
  86.  
Dec 6 '10 #1

✓ answered by gershwyn

In ASCII, the { character follows immediately after lowercase z. When you're generating a random number, you're asking for a value between 0 and 26 inclusive, which gives you 27 possibilities total.

Try changing line 78 to
Expand|Select|Wrap|Line Numbers
  1. randomInt = random.randint(0, 25)
and see where that gets you.

Share this Question
Share on Google+
7 Replies


100+
P: 122
In ASCII, the { character follows immediately after lowercase z. When you're generating a random number, you're asking for a value between 0 and 26 inclusive, which gives you 27 possibilities total.

Try changing line 78 to
Expand|Select|Wrap|Line Numbers
  1. randomInt = random.randint(0, 25)
and see where that gets you.
Dec 6 '10 #2

P: 32
Worked like a charm. Thank you! :]

Also, if it isn't too much to ask. How would I format this:
Expand|Select|Wrap|Line Numbers
  1. try:
  2.             randomize(passwordLength, passwordAmount, fileToWrite)
  3.             if True:
  4.                 showwarning("Random Password Generator", "Passwords Created! Check your folder!")
  5.  
So it would say "Passwords Created! Check your folder for (file name)!"
Dec 6 '10 #3

bvdet
Expert Mod 2.5K+
P: 2,851
Expand|Select|Wrap|Line Numbers
  1. showwarning("Random Password Generator", "Passwords Created! Check your folder for %s!" % fileToWrite)
Randomly generated passwords are often made from a combination of digits, upper case letters and lower case letters.
Expand|Select|Wrap|Line Numbers
  1. >>> import string
  2. >>> import random
  3. >>> passwordLen = 8
  4. >>> seq = string.digits+string.ascii_letters
  5. >>> "".join([random.choice(seq) for i in range(passwordLen)])
  6. 'v5JuKQoT'
  7. >>> 
Dec 6 '10 #4

Expert 100+
P: 621
You can use a loop to create the 3 labels if you want.
Expand|Select|Wrap|Line Numbers
  1.         for ctr, lit in enumerate(["Password Lengths Wanted:", "Password Amount Wanted:", "File Name:"]):
  2.             siteLabel = Label(self, text=lit, anchor = E, width = 20)
  3.             siteLabel.grid(row = ctr, column = 0) 
Also, you have 2 separate varaibles named "count". The second one does nothing here and can be deleted.
Expand|Select|Wrap|Line Numbers
  1. def randomize(length, amount, fileToWrite):
  2.     for num in xrange(amount):
  3.         newPassword = ""
  4.         for count in xrange(length):
  5.             randomInt = random.randint(0,26)
  6.             newPassword += chr(randomInt+97)
  7.             ## this does nothing so it can be deleted            
  8.             count += 1 
Dec 7 '10 #5

P: 32
Thanks bvdet! Your answers are always short, sweet and get right to the point!
How would I implement your code to making the password more random?
Dec 7 '10 #6

bvdet
Expert Mod 2.5K+
P: 2,851
Sorry it took so long to respond.

I would rewite function randomize as follows:
Expand|Select|Wrap|Line Numbers
  1. import string, random
  2.  
  3. def randomize(length, amount, fileToWrite):
  4.     seq = string.digits+string.ascii_letters
  5.     fileToWrite.write("\n".join(["".join([random.choice(seq) \
  6.                                           for i in range(length)]) \
  7.                                               for i in xrange(amount)]))
  8.     fileToWrite.close()
Note that writing to the file once is much faster than writing to the file for each password. The same thing holds true for print.
Dec 9 '10 #7

P: 32
Thanks again for the help bvdet! It worked out great!
Dec 9 '10 #8

Post your reply

Sign in to post your reply or Sign up for a free account.