Skip to content

Instantly share code, notes, and snippets.

@digi9ten
Last active December 15, 2018 21:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save digi9ten/ad54f0552c11da87a31cfcfbc472c2b6 to your computer and use it in GitHub Desktop.
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.
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