Welcome, guest | Sign In | My Account | Store | Cart

This is a code snippet to generate an 8 character alphanumeric password.

Python, 11 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
from whrandom import choice
import string

def GenPasswd():
    chars = string.letters + string.digits
    for i in range(8):
        newpasswd = newpasswd + choice(chars)
    return newpasswd

def GenPasswd2(length=8, chars=string.letters + string.digits):
    return ''.join([choice(chars) for i in range(length)])

Useful when you're creating new user accounts and want to assign them a random password.

The GenPasswd2 version allows one to specify the length of the password and the character sets to use to choose from, and shows off how to use list comprehensions to eliminate for loops.

>>> GenPasswd2()
'Bq1RVx1y'
>>> GenPasswd2(12)
'HpRGxrmzpg4V'
>>> GenPasswd2(12, string.letters)
'wIfJWRjYWCYu'

6 comments

Diana McC 20 years, 2 months ago  # | flag

How do you use it? I am interested in your snippet of code. But as I an an extream newbe I need a little hand holding to get it going. And suggestions? Thatnks Diana. diana_org@hotmail.com

Alex Martelli 20 years, 1 month ago  # | flag

it's easy to use this module. save it as a textfile, say makepass.py in some directory on your sys.path, then from any Python script, or interactively (in the Python interpreter, IDLE, etc):

import makepass
print makepass.GenPasswd2()

and similar uses. Write help@python.org for any more help request!

Juan Stang 16 years, 11 months ago  # | flag

Bug. Fun little snippet, comes in handy, but there's a little bug, of course ;)

The var 'newpasswd' is being created inside the 'for', and so may not be returned. The correct snippet should be:

def GenPasswd():
    chars = string.letters + string.digits
    newpasswd = ''
    for i in range(8):
        newpasswd = newpasswd + choice(chars)
    return newpasswd

That should do it ...

Rudolph Froger 15 years, 1 month ago  # | flag

Even shorter. How about:

return ''.join([choice(chars) for i in xrange(8)])
Bartosz Ptaszynski 14 years, 1 month ago  # | flag

Easier way :). Hey this is an easier way:

<pre lang="python"> import string from random import Random

newpasswd = ''.join( Random().sample(string.letters+string.digits, 12) ) </pre>

Cheers

GDR! 11 years, 2 months ago  # | flag

@Bartosz, random.sample does not handle repetitions. That is, each character from input sequence will appear at most once in output sequence.

Not only this is less random than original method, it also doesn't allow creating string longer than len(chars).