Python隨機生成驗證碼的方法有很多,今天給大家列舉兩種,大家也可以在這個基礎上進行改造,設計出適合自己的驗證碼方法方法一:利用range
Python隨機生成驗證碼的方法有很多,今天給大家列舉兩種,大家也可以在這個基礎上進行改造,設計出適合自己的驗證碼方法
方法一:
利用range方法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
# -*- coding: utf-8 -*-
import
random
def
generate_verification_code(
len
=
6
):
''' 隨機生成6位的驗證碼 '''
# 注意: 這里我們生成的是0-9A-Za-z的列表,當然你也可以指定這個list,這里很靈活
# 比如: code_list = ['P','y','t','h','o','n','T','a','b'] # PythonTab的字母
code_list
=
[]
for
i
in
range
(
10
):
# 0-9數字
code_list.append(
str
(i))
for
i
in
range
(
65
,
91
):
# 對應從“A”到“Z”的ASCII碼
code_list.append(
chr
(i))
for
i
in
range
(
97
,
123
):
#對應從“a”到“z”的ASCII碼
code_list.append(
chr
(i))
myslice
=
random.sample(code_list,
len
)
# 從list中隨機獲取6個元素,作為一個片斷返回
verification_code
=
''.join(myslice)
# list to string
return
verification_code
|
方法二:
利用randint方法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
# -*- coding: utf-8 -*-
import
random
def
generate_verification_code_v2():
''' 隨機生成6位的驗證碼 '''
code_list
=
[]
for
i
in
range
(
2
):
random_num
=
random.randint(
0
,
9
)
# 隨機生成0-9的數字
# 利用random.randint()函數生成一個隨機整數a,使得65<=a<=90
# 對應從“A”到“Z”的ASCII碼
a
=
random.randint(
65
,
90
)
b
=
random.randint(
97
,
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
|
測試:
1
2
3
4
|
code
=
generate_verification_code(
6
)
code2
=
generate_verification_code_v2()
print
code
print
code2
|
輸出結果:
1
2
|
Glc5Tr
Hr6t7B
|
我個人更傾向於第一種方法,更加靈活,可以隨意設置驗證碼長度。