D21-9random模块
import random res = random.random() print(res) 打印结果为 0-1之间的随机浮点数
打印1-3之间随机数
res = random.randint(1,3) print(res) 打印结果为1-3随机整数
打印1-2之间随机整数 range 左闭右开
res = random.randrange(1,3) print(res)
res = random.choice([1,2,3,43,5]) #传入的是列表 print(res)
res = random.sample([1,2,3,4,5],2) #随机选取两个
print(res)
res = random.uniform(1,3) #取任意范围的浮点数 print(res)
打乱次序
ret = [1,3,4,5,2,] random.shuffle(ret) print(ret) 打印结果 [3, 4, 5, 1, 2]
随机验证码
def v_code(): ret = '' for i in range(4): num = random.randint(0,9) alf = chr(random.randint(65,122)) #大小写字母 65-122是对应assic码的值 s = str(random.choice([num,alf])) ret += s return ret print(v_code())
补充+=字符串拼接
字符串连接 >>> a='1' >>> b='2' >>> a+=b >>> a '12'