>>> chars = string.ascii_letters + string.digits
>>> print(chars)
abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789
生成所有字母和数字干什么?在哪个场景中会用到呢,举个例子:比如生成激活码(优惠券),激活码一般都是字母和数字组成的,首先要有一个所有字母和数字的字符串,然后随机取出几个字母或数字。
import random, string
def rand_str(num, length=7):
f = open(‘Activation_code.txt‘, ‘w‘)
for i in range(num):
chars = string.ascii_letters + string.digits
s = [random.choice(chars) for i in range(length)]
f.write(‘{0}\n‘.format(‘‘.join(s)))
f.close()
if __name__ == ‘__main__‘:
rand_str(200)
wz0dajI
25vlulV
zLHkx9Y
GGzu0Ip
RilbYKW
4WZL2IC
4syobYw
kCMky7O
oUPde55
KrMRmUX
Ct0W2Pm
wMwpPdk
ydPuy9h
Z7vo3r9