台北來的土包子
 
Python -Random Password Generator 密碼產生器

Python -Random Password Generator 密碼產生器

密碼這東西和我們的日常生活習習相關,每個人幾乎每天都會使用到

每個網站對密碼的要求大概都是: 大寫字母,小寫字母,數字再加上符號

因應這個需求,我們利用 Python 來產生隨機的密碼

import random

seed = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!\"#$%&'()*+,-./:;<=>?@[\]^_`{|}~"

pwd = ''
for i in range(12):
    pwd = pwd + random.choice(seed)
print (pwd)

seed 是密碼的字元種子,利用random.choice 的方法在迴圈中隨機找出 12 前字,並放入 pwd 的變數中,最後再把結果用 print 輸出。

也可以是第二種寫法:

import random
import string

digtals = string.digits
words  = string.ascii_letters 
punctuations = string.punctuation

seed = digtals + words + punctuations 

pwd  = ''.join(random.sample(seed,12))
print (pwd)

第二種寫法捨棄了迴圈,直接利用 random.sample 產生亂數

string.digits 是數字 : 是 0123456789
string.ascii_letters 是文字: 大小寫的英文字母
string.punctuation 是符號: !”#$%&'()*+,-./:;<=>?@[]^_`{|}~

詳細的說明可參考 string — Common string operations — Python 3.10.1 documentation

發表迴響