在瀏覽別人博客時學習了random模塊,手癢自我練習下,寫個隨機生成指定長度的密碼字符串的函數,拿出來供各位參考:
廢話不多說,上代碼:
# coding: utf-8 import random import string SPECIAL_CHARS = '~%#%^&*' PASSWORD_CHARS = string.ascii_letters + string.digits + SPECIAL_CHARS def generate_random_password(password_length=10): """ 生成指定長度的密碼字符串,當密碼長度超過3時,密碼中至少包含: 1個大寫字母+1個小寫字母+1個特殊字符 :param password_length:密碼字符串的長度 :return:密碼字符串 """ char_list = [ random.choice(string.ascii_lowercase), random.choice(string.ascii_uppercase), random.choice(SPECIAL_CHARS), ] if password_length > 3: # random.choice 方法返回一個列表,元組或字符串的隨機項 # (x for x in range(N))返回一個Generator對象 # [x for x in range(N)] 返回List對象 char_list.extend([random.choice(PASSWORD_CHARS) for _ in range(password_length - 3)]) # 使用random.shuffle來將list中元素打亂 random.shuffle(char_list) return ''.join(char_list[0:password_length]) def test_password_generate(): random_password = generate_random_password(password_length=6) print(random_password) test_password_generate()
打完手工,上妹子: