python random 模块---随机生成用户名,长度由用户输入,产生多少条也由用户输入,用户名必须由大写字母、小写字母、数字组成

random模块是Python中常用来生成随机数或随机字符串的一个模块。比如你想测试一个登陆接口,需要批量生一些用户名,应户名包括大写字母、小写字母和数字,每个用户名不能重复,这件事就可以交给Python random来实现。

先说一下random的基本用法:

import random,string
print(random.random()) #用于生成0-1之间的随机浮点数
print(random.uniform(1,3)) #用于生成一个1-3之间(指定范围内)的随机浮点数
print(random.randint(0,20))#用于生成0-20之间的随机整数
print(random.randrange(1,10))#用于生成一个范围,可以加上步长值,如下
print(random.randrange(2,10,2)) #在2-10之间随机取数,每个数都是2+n*2的值,即只能是2、4、6、8、10这几个数,结果与random.choice(rango())等效
print(random.choice(range(1,10,2))) #在1-10之间随机取数,每个数都是1+n*2的值,即只能是1、3、5、7、9这几个数,结果与random.randrange(*,*,*)等效
print(random.choice(string.ascii_lowercase)) #随机选取a-z之间的一个字母
print(random.choice(string.ascii_uppercase)) #随机选取A-Z之间的一个字母
print(random.choice(string.ascii_letters)) #随机选取a-z和A-Z之间的字母
print(''.join(random.sample('abcdefg12345',6))) #结果为4acg21
print(random.sample('abcdefg12345',6)) #结果为['4', '2', 'c', 'g', '5', '1']

 

生成一定个数的用户名代码如下(下面代码是生成5个8位长度的用户名):

import random,string,re
def username(lenght,sum): #lenght用户名长度,#sum用户名个数
    uname_new=''
    all_uname=[]
    while sum>0:
        str = []
        lenght1=lenght
        while lenght1>0:
            uname = random.choice(string.ascii_letters+'1234567890')
            str.append(uname)
            uname_new = ''.join(str)
            lenght1 -=1
        if re.match('^[A-Z][a-z][0-9]',uname_new): #包含大写、小写、数字的用户名写到all_uname里面
            all_uname.append(uname_new)
            sum -= 1
    print(all_uname)
username(8,5)

还有一种比较方便的方法可以用random.sample(),代码直接可以定义生成的字符串长度

print(''.join(random.sample('abcdefg12345',6))) #结果为4acg21
print(random.sample('abcdefg12345',6)) #结果为['4', '2', 'c', 'g', '5', '1']

 

def username_RandomSample(lenght,sum):
    all_uname=[]
    while sum>0:
        uname = ''.join(random.sample('abcdefghijklmnopqrstuvwxyzABCDEFGHIGKLMNOPQRSTUVWXYZ0123456789',lenght))
        #if re.match('[A-Z]',uname) and re.match('[a-z]',uname) and re.match([0-9]): #包含大写、小写、数字的用户名写到all_uname里面
        if re.match('[a-z][A-Z][0-9]',uname):
            all_uname.append(uname)
            sum -= 1
    print(all_uname)
username_RandomSample(3,5)

 

posted on 2017-09-04 22:47  yuer011  阅读(1285)  评论(0编辑  收藏  举报

导航