1

Is there any module in Python for generating random strings but to be unique ? I need to generate keys like for example when installing Windows.

Damir
  • 54,277
  • 94
  • 246
  • 365
  • 2
    Sorry, ignore my previous. Are you looking for http://stackoverflow.com/questions/534839/how-to-create-a-guid-in-python? – Ben Jun 11 '13 at 23:11
  • to generate a random bytestring (not necessarily unique), you could use `os.urandom(size)`. `ssl.RAND_bytes(size)` (Python 3.3) provides cryptographically strong pseudo-random bytes. – jfs Jun 11 '13 at 23:42

2 Answers2

12

Since you haven't specified the format of the string you want to get, I suppose it doesn't matter, so I suggest simply using UUIDs.

>>> import uuid
>>> str(uuid.uuid4())
  > '3afc84bb-6d73-4482-806a-6b3a29e43bca'
kirelagin
  • 13,248
  • 2
  • 42
  • 57
2

Well if you want only letters, for example, here's code to generate a random string of a random length upto 1000:

out = ''
for i in range(random.random()*100):
    out += random.choice('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvqxyz')

You can modify your alphabet of course.

akshat
  • 156
  • 1
  • 2