There are many ways for Python to generate a random verification code at random. today we will list two methods for you to generate a random verification code. you can also modify them on this basis and design a suitable verification code method.
Method 1:
For details about the range method, see the range () function developed by python.
#-*-Coding: UTF-8-*-import randomdef generate_verification_code (len = 6): ''' a 6-digit verification code is randomly generated ''' # note: here we generate a list of 0-9A-Za-z. of course, you can also specify this list, which is flexible # for example: code_list = ['P', 'y', 'T ', 'H', 'O', 'n', 'T', 'A', 'B'] # The PythonTab letter code_list = [] for I in range (10 ): #0-9 digit code_list.append (str (I) for I in range (65, 91): # corresponds to the ASCII code code_list.append (chr (I) from "A" to "Z )) for I in range (97,123): # corresponds to the ASCII code code_list.append (chr (I) from "a" to "z" myslice = random. sample (code_list, len) # randomly obtain 6 elements from the list and return verification_code = ''as a piece ''. join (myslice) # list to string return verification_code
Method 2:
Use the randint method #-*-coding: UTF-8-*-import randomdef generate_verification_code_v2 (): '''randomly generate a 6-digit verification code ''' code_list = [] for I in range (2): random_num = random. randint (0, 9) # randomly generate 0-9 numbers # use random. the randint () function generates a random integer a so that 65 <= A <= 90 # corresponds to the ASCII code a = random from "a" to "Z. randint (65, 90) B = random. randint (97,122) comment = chr (a) comment = chr (B) code_list.append (str (random_num) code_list.append (comment) 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, which is more flexible and can set the verification code length at will.