PDA

View Full Version : [SOLVED] [Python] Random string generation



ki4jgt
May 8th, 2011, 05:31 AM
How do you generate a random string in Python? Stackoverflow and a couple of other sites suggest a really long line of code to achieve this but when I plug it into Python and (Importing the modules and substituting length) I get errors (Away from console right now)

simeon87
May 8th, 2011, 10:53 AM
This gives pretty random strings:


from hashlib import sha1
from random import random
print sha1(str(random())).hexdigest()

ziekfiguur
May 8th, 2011, 12:31 PM
import string
import random
size = 20 # or whatever lenght you want your random string to be
allowed = string.ascii_letters # add any other allowed characters here
randomstring = ''.join([allowed[random.randint(0, len(allowed) - 1)] for x in xrange(size)])
print randomstring

This works too, but also allows you to have other characters than only hexadecimal numbers and can be used to generate strings of any length.

ki4jgt
May 8th, 2011, 09:46 PM
import string
import random
size = 20 # or whatever lenght you want your random string to be
allowed = string.ascii_letters # add any other allowed characters here
randomstring = ''.join([allowed[random.randint(0, len(allowed) - 1)] for x in xrange(size)])
print randomstring

This works too, but also allows you to have other characters than only hexadecimal numbers and can be used to generate strings of any length.

Thanks