Vijay Dev Vijay Dev - 6 months ago 45
Python Question

Generating random text strings of a given pattern

I need to generate random text strings of a particular format. Would like some ideas so that I can code it up in Python. The format is <8 digit number><15 character string>.

Jay Jay

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.