Friday, December 22, 2006

Python : Generate Random Strings

I like Python. More and more :) Here is example of random string generation :

import random
alphabet = 'abcdefghijklmnopqrstuvwxyz'
min = 5
max = 15
total = 1000000
FILE = open("filename.out","w")
for count in xrange(1,total):
for x in random.sample(alphabet,random.randint(min,max)):

It's rather shorter than adequate Java application. It seems to be that doing less we can take more :). The key is the random.sample(A,N) function - it is return random subset of A with N elements. Since I need random strings with random length varies from 5 to 15, I'm using N as random.randint(min,max).
There may be more elegant solution but this is works for me :)


Elad Gariany said...

Thanks a lot.
Thats really helped me.

Stas Ostapenko said...

Hi Elad, you're welcome ! Thanks for comment !

Anonymous said...

import string
import random
"".join(random.sample(string.letters+string.digits, 8))

does the trick

Stas Ostapenko said...

Thanks for comment ! I didn't know about string.letters & string.digits. Useful hint, thanks.

Utilitopia said...

I don't think the "".join(..) technique is random - it only produces strings that contain a given character once, and it doesn't work for generating strings longer than the number of characters available.

MasterPi said...

import string
import random
"".join([random.choice(string.letters+string.digits) for x in range(1, desired_length)])

Ulrich said...

Anonymous' solution uses every letter only once.

MasterPi's solution is close to be correct. You should use range(disered_length) instead of beginning with 1.

William said...


Anonymous' solution is fine. random.sample samples from the population without replacement. It returns a list, and the join method concatenates the list to a string.

Anonymous said...

''.join((random.choice(string.letters+string.digits) for _ in xrange(random.randint(min_len,max_len))))

The solution originally posted by MasterPi, but takes advantage of generators and has lower memory requirements.

taredhot said...

you could use the string package:
import string

returns lower/uppercase alphabet

enjoy ;)