Mariusz Andrzejewski
Mariusz Andrzejewski

Reputation: 39

Password generator (defining character set and length of password with random length range)

I have this short code extract of a password generator. You can see here it's using the random function to produce a 13 char length password.

One, that line beginning chars is a bit messy. Is there any other ways of expressing character ranges or sets? Perhaps if I just wanted to have alpha characters or something? (Would that just be removing the symbols at the end of the line, because alpha characters is 0-9 and A-Z?)

Secondly, I guess a much more straight forward question. I'm trying to use the random function to generate a random length of password? In pseudocode I imagine it to be something like

password.length = rand(5-10)

but I don't have much experience with ranges yet.

Here's the code I am running for the password generator.

import os, random, string

length = 13
chars = string.ascii_letters + string.digits + '!@#$%^&*()'
random.seed = (os.urandom(1024))

print ''.join(random.choice(chars) for i in range(length))

If anyone could shed some light on a simpler way of defining a character set or preferrably just alpha characters (IE A-Z and 0-9) that'd be great.

Upvotes: 0

Views: 1261

Answers (3)

Rational Function
Rational Function

Reputation: 435

This alternative to my other answer would only use alpha-numeric characters in the password.

import random
length=13
ListOfChars=[]
codes=list(range(48,57))+list(range(65,90))+list(range(97,122))
for a in range(length):
    ASCIIcode=random.choice(codes)
    ListOfChars.append(chr(ASCIIcode))
print(''.join(ListOfChars))

Upvotes: 1

Rational Function
Rational Function

Reputation: 435

import random
length=13
ListOfChars=[]
for a in range(length):
    ASCIIcode=random.randint(32,126)
    ListOfChars.append(chr(ASCIIcode))
print(''.join(ListOfChars))

This will create a password, which only uses keys available on a standard keyboard.

Upvotes: 1

Brian
Brian

Reputation: 737

Like this?

import string
import random

def id_generator(size=13, chars=string.ascii_uppercase + string.digits):
    return ''.join(random.choice(chars) for _ in range(size))

print "Your password is: ", id_generator()

Upvotes: 1

Related Questions