#!/usr/bin/env python
#-*-coding:utf-8-*-
# No. 0001: As an independent developer of the Apple Store app, you need to engage in limited-time promotions to generate an activation code (or coupon) for your app.
# How do I generate 200 activation codes (or coupons) using Python?
Import string
Import Random
Key_len = 20
Key_all = 200
Def base_str ():
Return (string.ascii_letters + string.digits) #生成所有的字母和数字
Def Key_gen ():
Key_list = [Random.choice (Base_str ()) for I in Range (Key_len)] #随机选择上一个函数生成的字母和数字, generates a sequence of length 20
Return ('. Join (key_list)) #合并序列里面的内容, does not merge is this way [' f ', ' Z ', ' V ', ' V ', ' z ', ' d ', ' n ', ' C ', ' 1 ', ' 1 ', ' I ', ' K ', ' B ', ' I ', ' G ', ' 5 ', ' d ', ' Z ', ' Q ', ' L ']
def key_num (Num,result=none):
If result is None: #这一句估计就是用来创建一个空列表, delete this sentence directly create an empty list can also be used, it doesn't feel necessary to be so complicated
result = []
For I in range (num):
Result.append (Key_gen ()) #将key_gen () The generated activation code is added to this empty list, adding num
return result
def print_key (num):
For i in Key_num (num):
Print (i) #打印出result中的每一个元素
If __name__== ' __main__ ':
Print_key (Key_all) #调用函数
Knowledge to be used: reprinted from: https://blog.tanteng.me/2015/07/python3-ascii-letters/
This article describes the string module ascii_letters and digits methods in Python3, where ascii_letters is generating all the letters, from A-Z and a-z,digits are generated for all numbers 0-9.
Examples are as follows:
>>> chars = string. Ascii_letters + string. Digits >>> print(chars) abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789
Generate all the letters and numbers for what? In which scenario will it be used, for example: Generate an Activation Code (coupon), the activation code is generally composed of letters and numbers, the first to have a string of all letters and numbers, and then randomly remove a few letters or numbers.
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 = [< Span class= "crayon-k" >random. Choice (chars for i in range (length] F. Write(' {0}\n '). Format('. Join(s))) F. Close() if __name__ = = ' __main__ ': rand_str($)
Execution result Fragment:
Wz0daji
25vlulV
Zlhkx9y
Ggzu0ip
rilbykw
4wzl2ic
4syobYw
Kcmky7o
OUPde55
Krmrmux
ct0w2pm
Wmwppdk
ydpuy9h
Z7vo3r9
EmcmQl0
GeIDKw3
Pk9blvg
Z4xndvb
I0ega9o
Ypuh5ua
69gISVt
Xun7gi3
YufPaD0
dsyzx2q
3jfw1bh
YdHELg6
Nxnmrba
20170512 Python workbook 0001 generate an activation code