Generating random text strings of a given pattern

2019-01-17 01:39发布

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>.

4条回答
地球回转人心会变
2楼-- · 2019-01-17 01:47

random.sample is an alternative choice. The difference, as can be found in the python.org documentation, is that random.sample samples without replacement. Thus, random.sample(string.letters, 53) would result in a ValueError. Then if you wanted to generate your random string of eight digits and fifteen characters, you would write

import random, string

digits = ''.join(random.sample(string.digits, 8))
chars = ''.join(random.sample(string.letters, 15))
查看更多
地球回转人心会变
3楼-- · 2019-01-17 01:58
#!/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.

查看更多
Fickle 薄情
4楼-- · 2019-01-17 02:02

Here's a simpler version:

import random
import string

digits = "".join( [random.choice(string.digits+string.letters) for i in   xrange(10)] )
print digits
查看更多
贼婆χ
5楼-- · 2019-01-17 02:11

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'
>>> 
查看更多
登录 后发表回答