Random strings in Python 2.6 (Is this OK?) Random strings in Python 2.6 (Is this OK?) python python

Random strings in Python 2.6 (Is this OK?)


import osrandom_string = os.urandom(string_length)

and if you need url safe string :

import osrandom_string = os.urandom(string_length).hex() 

(note random_string length is greatest than string_length in that case)


Sometimes a uuid is short enough and if you don't like the dashes you can always.replace('-', '') them

from uuid import uuid4random_string = str(uuid4())

If you want it a specific length without dashes

random_string_length = 16str(uuid4()).replace('-', '')[:random_string_length]


Taken from the 1023290 bug report at Python.org:

junk_len = 1024junk =  (("%%0%dX" % junk_len) % random.getrandbits(junk_len *8)).decode("hex")

Also, see the issues 923643 and 1023290