Generating random text strings of a given pattern

See an example - Recipe 59873: Random Password Generation .

Building on the recipe, here is a solution to your question :

from random import choice
import string

def GenPasswd2(length=8, chars=string.letters + string.digits):
    return ''.join([choice(chars) for i in range(length)])

>>> GenPasswd2(8,string.digits) + GenPasswd2(15,string.ascii_letters)
'28605495YHlCJfMKpRPGyAw'
>>> 

#!/usr/bin/python

import random
import string

digits = "".join( [random.choice(string.digits) for i in xrange(8)] )
chars = "".join( [random.choice(string.letters) for i in xrange(15)] )
print digits + chars

EDIT: liked the idea of using random.choice better than randint() so I've updated the code to reflect that.

Note: this assumes lowercase and uppercase characters are desired. If lowercase only then change the second list comprehension to read:

chars = "".join( [random.choice(string.letters[:26]) for i in xrange(15)] )

Obviously for uppercase only you can just flip that around so the slice is [26:] instead of the other way around.