生成给定模式的随机文本字符串 [英] Generating random text strings of a given pattern
问题描述
我需要生成特定格式的随机文本字符串.想一些想法,以便我可以用Python编写代码.格式为< 8位数字>< 15字符串>.
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>.
推荐答案
#!/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
喜欢比randint()更好地使用random.choice的想法,所以我更新了代码以反映这一点.
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)] )
显然,对于大写字母,您只需将其翻转即可,使切片为[26:],而不是相反.
Obviously for uppercase only you can just flip that around so the slice is [26:] instead of the other way around.
这篇关于生成给定模式的随机文本字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!