版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u010039418/article/details/86013620
需求
随机生成定长的小写字母和数字组合。
实现
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import random
def getRandomSet(bits):
num_set = [chr(i) for i in range(48,58)]
char_set = [chr(i) for i in range(97,123)]
total_set = num_set + char_set
value_set = "".join(random.sample(total_set, bits))
return value_set
if __name__ == '__main__' :
strings = getRandomSet(26)
print(strings)
分析
1、首先使用chr()函数,生成小写字母和数字两个列表
2、合并两个列表
3、使用random模块的sample采样函数,随机采集指定位数的字符。
4、random采样的结果是列表,还需要转换成str类型,使用str的join函数即可。
效果
[root@CentOS-7-2 /home]# python genrandom.py
f0wzxl8pqgtikmdo9ybascnj76
[root@CentOS-7-2 /home]# python genrandom.py
q910vxfij4to23r6gy87phewnd
[root@CentOS-7-2 /home]# python genrandom.py
rtzmvyeul81gqjcso63b2hx509