Last active
December 15, 2018 21:12
-
-
Save digi9ten/9de110c64c455cef478b30fbd93bb9bd to your computer and use it in GitHub Desktop.
Within Python 2.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 | |
USABLE_SEQUENCE_WITH_LOWER = string.ascii_letters + string.digits | |
USABLE_SEQUENCE_WITHOUT_LOWER = string.ascii_uppercase + string.digits | |
def generate_secret(length=40, 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 xrange(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(), "") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Joseph Wright pointed out a better way to combine the found items into the resulting string