How to generate random strings with upper case letters and digits in Python?

PythonServer Side ProgrammingProgramming

You can use random.choice(list_of_choices) to get a random character. Then loop over this and get a list and finally join this list to get a string. The list of choices here is Upper case letters and digits. For example:

import string
import random
def get_random_string(length):
    random_list = []
    for i in xrange(length):
        random_list.append(random.choice(string.ascii_uppercase + string.digits))
    return ''.join(random_list)
print get_random_string(10)

This will give us the output:


This can also be achieved in a single line:

>>> ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in xrange(10))

In Python 3, we have a random. choices method which takes the second argument as the length of random string. It can be used to get an even shorter version:

>>> ''.join(random.choices(string.ascii_uppercase + string.digits), k=10)
Published on 13-Dec-2017 11:30:56