Last active
December 15, 2018 21:39
-
-
Save digi9ten/ad54f0552c11da87a31cfcfbc472c2b6 to your computer and use it in GitHub Desktop.
Within Python 3.X, produces a random, alphanumeric string of desired length, with optional mixed case.
This file contains 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
import string | |
import random | |
from functools import reduce | |
USABLE_SEQUENCE_WITH_LOWER = string.ascii_letters + string.digits | |
USABLE_SEQUENCE_WITHOUT_LOWER = string.ascii_uppercase + string.digits | |
def generate_secret(length=50, mixed_case=False): | |
""" | |
Produces a random, alphanumeric string of a desired length. | |
:param length: the length of the produced string. | |
:param mixed_case: If True, the resulting string may have mixed-case. | |
:return: A random, alphanumeric string of a desired length | |
""" | |
if not isinstance(length, int): | |
raise RuntimeError("length must be a number greater than 0") | |
def inner_gen(): | |
for x in range(length): | |
if mixed_case: | |
yield random.choice(USABLE_SEQUENCE_WITH_LOWER) | |
else: | |
yield random.choice(USABLE_SEQUENCE_WITHOUT_LOWER) | |
return reduce(lambda x, y: x + y, inner_gen(), "") | |
if __name__ == "__main__": | |
print(generate_secret()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment