随机生成指定位数的验证码
import random
import string
# 方法一:
def code_1(m, choice):
code=''.join(random.sample(choice, m))
return code
print(code_1(4, string.ascii_letters + string.digits))
# 方法二:
def code_2(n):
code=''
for i in range(n):
number=random.randint(0, 9) # 0-9
lower_char=chr(random.randint(97, 122)) # a-z
upper_char=chr(random.randint(65, 90)) # A-Z
char_1=random.choice([number, lower_char, upper_char])
code+=str(char_1)
return code
print(code_2(4)
先上代码。。。高效如我 ^ ^..。颜色怪怪的、不要介意哈~
Random详解
随机产生一个1-100之间的整数
print(random.randint(1,100))
随机产生一个0-100之间的奇数
print(random.randrange (0,100,2))
随机产生一个0-100之间的偶数
print(random.randrange ( 1 , 100 , 2))
随机产生一个浮点数
print(random.random())
print(random.uniform(1,10))
随机选择一个字符
print(random.choice(r'qwertyuiop[]\asdfghjkl;zxcvbnm,./'))
随机生成指定数量的字符
print(code=''.join(random.sample(choice, m)))
其中choice为备选字符串,m为生成的验证码个数