Random passwords generation (Python vs Perl) =)

Paul McGuire ptmcg at austin.rr.com
Mon Jan 29 04:51:42 EST 2007


On Jan 28, 10:58 pm, "NoName" <zaz... at gmail.com> wrote:
> Perl:
> @char=("A".."Z","a".."z",0..9);
> do{print join("", at char[map{rand @char}(1..8)])}while(<>);
>
> !!generate passwords untill U press ctrl-z
>
> Python (from CookBook):
>
> from random import choice
> import string
> print ''.join([choice(string.letters+string.digits) for i in
> range(1,8)])
>
> !!generate password once :(
>
> who can write this smaller or without 'import'?

from random import choice
pwdchars = ''.join(chr(c) for c in range(ord('a'),ord('z')+1)+
                    range(ord('A'),ord('Z')+1)+
                     range(ord('0'),ord('9')+1) )

while(True) : print ''.join(choice(pwdchars) for i in range(8))


(Note that you want to use range(8), not range(1,8), since range gives 
you the values [a,b) if two arguments are given, or [0,a) if only one 
is given, and it appears that you want 8-character passwords.)

But really, there's nothing wrong with using import, and reusing known 
good code from the string module is better than reimplementing it in 
new code as I have done (less code === fewer opportunities for bugs).  
rand is not a built-in as it apparently is in Perl, but random is part 
of the core library, so all Python installs will have it available - 
likewise for string.

-- Paul




More information about the Python-list mailing list