需求:隨機(jī)生成優(yōu)惠券或激活碼
import string
import random
forSelect = string.ascii_letter + string.digits
def generate_code(count,length):
for x in range(count):
discount = ''
for y in range(length):
discount += random.choice(forSelect)
print(discount)
if __name__ = '__main__'
generate_code(200,30)
結(jié)果生成200個30位的隨機(jī)數(shù)
string庫中的ascii_letter方法是生成所有的a-z和A-Z;digits方法是生成0-9數(shù)字
>>>print(string.ascii_letter+string.digits)
abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789random中的choice方法每次返回字符串(列表、元組)中一個隨機(jī)項
>>>random.choice('stringgggggggg')
g