import random import string print(random.random()) #打印小数 print(random.randint(1,2))#随机打印其中 print(random.randrange(1,2))#永远不打印最后一个值 print(random.sample(range(100),5))#从100个数字里随机选择5个 print(string.ascii_letters)#大小写26个字母 print(string.digits)#0到9数字 ##结果## 0.434611704944574 2 1 [71, 6, 92, 88, 90] abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ 0123456789
示例:
简单的随机验证码例:
import random,string str_source=string.ascii_letters+string.digits print(''.join(random.sample(str_source,5))) ##结果### 3fqAX
示例2:
随机验证码4个字符:
checkcode='' for i in range(4): current=random.randrange(0,4) if current!=i: temp=chr(random.randint(65,90)) else: temp=random.randint(0,9) checkcode+=str(temp) print(checkcode) ##结果## 0UKT