Generate Random Characters With Python Using Random and String Modules
When generating random characters for whatever reason, passwords, secrets-keys etc, you could use the uuid module, which looks like this:
Random String with UUID
123
>>>fromuuidimportuuid4>>>print("Your string is: {0}".format(uuid4()))Yourstringis:53a6e1a7-a2c7-488e-bed9-d76662de9c5f
But if you want to be more specific, like digits, letters, capitalization etc, you can use the string and random modules to do so. First we will generate a random string containing only letters:
Random String with letters
123456789
>>>fromstringimportascii_letters,punctuation,digits>>>fromrandomimportchoice,randint>>>min=12>>>max=15>>>string_format=ascii_letters>>>generated_string="".join(choice(string_format)forxinrange(randint(min,max)))>>>print("Your String is: {0}".format(generated_string))YourStringis:zNeUFluvZwED
As you can see, you have a randomized string which will be always at least 12 characters and max 15 characters, which is lower and upper case. You can also use the lower and upper functions if you want to capitalize or lower case your string:
Let’s add some logic so that we can have a more randomized characters with digits, punctuations etc:
Random String with Letters, Punctuations and Digits
12345678
>>>fromstringimportascii_letters,punctuation,digits>>>fromrandomimportchoice,randint>>>min=12>>>max=15>>>string_format=ascii_letters+punctuation+digits>>>generated_string="".join(choice(string_format)forxinrange(randint(min,max)))>>>print("Your String is: {0}".format(generated_string))YourStringis:Bu>}x_/-H5)fLAr