記号、数字の割合を制御しながらランダムな文字列を生成する関数
import random
import string
from typing import List
def get_pw(length: int = 10, symbols: str = string.punctuation,
digit_ratio: float = 0.2, symbol_ratio: float = 0.2) -> str:
assert digit_ratio + symbol_ratio <= 1
def get_chars(length: int, candidates: str) -> List[str]:
return list(random.choice(candidates) for i in range(length))
digit_num = int(length * digit_ratio)
symbol_num = int(length * symbol_ratio)
letter_num = length - digit_num - symbol_num
chars = get_chars(digit_num, string.digits) \
+ get_chars(symbol_num, symbols) \
+ get_chars(letter_num, string.ascii_letters)
random.shuffle(chars)
return ''.join(chars)
print(get_pw()) # j4U*2fic=b
print(get_pw(8)) # XsR&Zu2j
print(get_pw(symbols='!-_')) # BpSX!_49mj
print(get_pw(digit_ratio=0.7)) # 146!X8@908