Random strings in Python

Generating strings from (for example) lowercase characters:

import random, string

def randomword(length):
   letters = string.ascii_lowercase
   return ''.join(random.choice(letters) for i in range(length))

Results:

>>> randomword(10)
'vxnxikmhdc'
>>> randomword(10)
'ytqhdohksy'

Since this question is fairly, uh, random, this may work for you:

>>> import uuid
>>> print uuid.uuid4()
58fe9784-f60a-42bc-aa94-eb8f1a7e5c17

>>> import random
>>> import string
>>> s=string.lowercase+string.digits
>>> ''.join(random.sample(s,10))
'jw72qidagk

Tags:

Python