python如何生成随机n位数字与字母组合(创建随机)
作者:wait a minutes
这篇文章主要介绍了python如何生成随机n位数字与字母组合(创建随机),具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
python生成随机n位数字与字母组合
环境
ubuntu python3.6 random
代码
(1)生成6位数字与字母组合
import random n = 6 def v_code(n=6): """ Returns: ret:random six num and letter """ ret = "" for i in range(n): num = random.randint(0, 9) # num = chr(random.randint(48,57))#ASCII表示数字 letter = chr(random.randint(97, 122)) # 取小写字母 Letter = chr(random.randint(65, 90)) # 取大写字母 s = str(random.choice([num, letter, Letter])) ret += s return ret
(2)生成6位字母组合
import random n = 6 def v_code1(n=6): """ Returns: ret:random six letter """ ret = "" for i in range(n): letter = chr(random.randint(97, 122)) # 取小写字母 Letter = chr(random.randint(65, 90)) # 取大写字母 s = str(random.choice([letter, Letter])) ret += s return ret
(3)生成6位数字组合
import random n = 6 def v_code2(n=6): """ Returns: ret:random six num """ ret = "" for i in range(n): num = random.randint(0, 9) s = str(random.choice([num])) ret += s return ret
(4)代码汇总
# -*- coding: UTF-8 -*- ''' @author: mengting gu @contact: 1065504814@qq.com @time: 2020/11/3 下午9:04 @file: random_num.py @desc: Get the combination of n numbers and upper and lower case letters. ''' import random n = 6 def v_code_nums_letters(n=6): """ Returns: ret:random six num and letter """ ret = "" for i in range(n): num = random.randint(0, 9) # num = chr(random.randint(48,57))#ASCII表示数字 letter = chr(random.randint(97, 122)) # 取小写字母 Letter = chr(random.randint(65, 90)) # 取大写字母 s = str(random.choice([num, letter, Letter])) ret += s return ret def v_code_letters(n=6): """ Returns: ret:random six letter """ ret = "" for i in range(n): letter = chr(random.randint(97, 122)) # 取小写字母 Letter = chr(random.randint(65, 90)) # 取大写字母 s = str(random.choice([letter, Letter])) ret += s return ret def v_code_nums(n=6): """ Returns: ret:random six num """ ret = "" for i in range(n): num = random.randint(0, 9) s = str(random.choice([num])) ret += s return ret print("v_code_nums_letters result: " + v_code_nums_letters()) print("v_code_letters result: " + v_code_letters()) print("v_code_nums result: " + v_code_nums())
结果样例:
python批量生成随机密码
需求:一次生成多个随机密码,密码强度:包含数字、大小写字母,18位。
import random import string # 先介绍下random怎么生成随机数和字母 # 产生一个随机整数 num = random.randint(0,10000) print(num) # 产生一个随机字母,注意是一个 str1 = random.choice(string.ascii_letters) print(str1) # 生成10个、18位随机密码,包含数字和字母大小写 def genPass(length): # string.ascii_letters: 生成a-Z字母 # string.digits:生成0-9的数字字符串 chars = string.ascii_letters + string.digits # 这个的意思是:从chars中获取一个随机的字符,这个字符可能是数字也可能是大小写的字母 # 然后for循环获取18次,再用join合并成一个字符串,所以就成了一个18位的密码 return ''.join([random.choice(chars) for i in range(length)]) if __name__ == '__main__': # 批量生成10个密码 for i in range(10): print(genPass(18))
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。