Python random generation of verification code method There are many, today to give you a list of two kinds, we can also be modified on this basis, design a suitable verification code method
Method One:
Use the Range method, for students who are not clear about the range method, please refer to the article "range () function developed by Python"
#-*-Coding:utf-8-*-import randomdef generate_verification_code (len=6): ' randomly generate 6-bit Verification code ' # Note: Here we generate a list of 0-9a-za-z, of course, you can also specify that this list, here is very flexible # for example: Code_list = [' P ', ' y ', ' t ', ' h ', ' o ', ' n ', ' t ', ' a ', ' B '] # Pythontab letters code_list = [] for I in range (10): # 0-9 digit code_list.append (str (i)) for I in range (65, 91): # on "a" to "Z" ASCII code code_list.append (Chr (i)) for I in range (123): ASCII code_list.append (Chr (i) #对应从 "a" to "Z" Myslice = Random.sample (code_list, Len) # randomly gets 6 elements from the list, returning as a fragment Verification_code = '. Join ( Myslice) # List to string return Verification_code
Method Two:
Using the Randint method #-*-Coding:utf-8-*-import randomdef generate_verification_code_v2 (): " randomly generate 6-bit verification code" Code_ List = [] for I in range (2): random_num = random.randint (0, 9) # randomly generates 0-9 numbers # Use the Random.randint () function to generate a random integer a, 65<=a<=90 # for ASCII code from "a" to "Z" a = Random.randint (+) B = Random.randint (122) Random_ Uppercase_letter = Chr (a) random_lowercase_letter = Chr (b) code_list.append (str (random_num)) Code_ List.append (Random_uppercase_letter) code_list.append (random_lowercase_letter) Verification_code = '. Join (code_list) return Verification_code
Test:
Code = Generate_verification_code (6) Code2 = GENERATE_VERIFICATION_CODE_V2 () print Codeprint Code2
Output Result:
glc5trhr6t7b
I personally prefer the first method, more flexible, can be arbitrarily set the length of the verification code.