Python Generate Random String With Examples

We can generate a random string in Python using the random module. Sometimes we want to generate a random string for unique identifiers, session id or to suggest a password.

Python Generate Random String

Let’s define the utility function to generate a random string from the given sequence of characters and specified size.


import random
import string
def random_string_generator(str_size, allowed_chars):
    return ''.join(random.choice(allowed_chars) for x in range(str_size))
chars = string.ascii_letters + string.punctuation
size = 12
print(chars)
print('Random String of length 12 =', random_string_generator(size, chars))

Output:


abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&'()*+,-./:;[email protected][]^_`{|}~
Random String of length 12 = 'MP'?EI$MO%w

We are using random.choice() function to select a random character from the provided sequence of characters. Then we are using for loop to run it given number of times. Then we are using string join() function to concatenate them and return the randomly generated string.

python-generate-random-string

What if we want to keep the random string size as variable, say between 8 and 12 characters. Let’s tweak our function little bit to randomly select the size of the random string.


import random
from random import randint
import string
def random_string_generator_variable_size(min_size, max_size, allowed_chars):
    return ''.join(random.choice(allowed_chars) for x in range(randint(min_size, max_size)))
chars = string.ascii_letters + string.punctuation
print('Random String of random length (6-12) =', random_string_generator_variable_size(6, 12, chars))

Output: Random String of random length (6-12) = d;@o/?[yq=

python-generate-random-string

The code is almost the same as earlier function except for the use of the randint() function. This is done to randomly select the size of the randomly generated string.

Random UUID Generation

If you want a Unique ID based on RFC-4122 specifications, then you can use Python uuid module.


import uuid
print('Random UUID from uuid1() =', uuid.uuid1())
print('Random UUID from uuid4() =', uuid.uuid4())

Output:


Random UUID from uuid1() = dcc1044e-d76b-11e8-b54e-186590db0e15
Random UUID from uuid4() = a0e98c8d-a6fd-4125-bc1c-69ffe6456cb6
python-generate-random-string
You can checkout complete python script and more Python examples from our GitHub Repository.

By admin

Leave a Reply

%d bloggers like this: