LoginSignup
1
0

More than 1 year has passed since last update.

パスワード用文字列生成関数 (Python3)

Last updated at Posted at 2019-06-15

記号、数字の割合を制御しながらランダムな文字列を生成する関数

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
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0