Created
June 14, 2018 02:41
-
-
Save mickm3n/76e9d2da00e2d1eb1a0b648966c73132 to your computer and use it in GitHub Desktop.
Python 2 generate random string with at least one character in each charset
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def generate_random_string(length, charsets=[string.ascii_uppercase, string.ascii_lowercase, string.digits, string.punctuation]): | |
system_random = random.SystemRandom() | |
dividers = sorted(system_random.sample(xrange(1, length), len(charsets) - 1)) | |
charset_lengths = [a - b for a, b in zip(dividers + [length], [0] + dividers)] | |
random_string = ''.join([''.join(system_random.choice(charset) for _ in range(charset_length)) for charset, charset_length in zip(charsets, charset_lengths)]) | |
return ''.join(system_random.sample(random_string, len(random_string))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment