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>.
+7
A:
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'
>>>
gimel
2008-12-15 06:18:07
+9
A:
#!/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.
Jay
2008-12-15 06:19:22
Nice answer! (I had never even seen random.choice before.)
Claes Mogren
2008-12-15 06:35:40
Keep the recipes as a bookmark - http://code.activestate.com/recipes/
gimel
2008-12-15 06:51:03
Probably more readable to use string.lowercase and string.uppercase than slicing the list. Also the solution only holds if the OP is satisfied with only ASCII characters, if he wants to generate strings from the whole unicode character set the problem becomes much harder.
Björn Lindqvist
2010-07-19 14:19:55