How to Implement a Random String Generator With Python

How to Implement a Random String Generator With Python

Learn how to use Python to create random strings in two different ways, including secure random strings

In this post, you'll learn how to create a random string in Python using different methods; but, beware! Some of them only work with Python 3.6+.

By the end of this article, you should be able to:

  • use the choice function to generate a random string from string.ascii_letters, string.digits + string.punctuation characters in Python 3
  • generate a secure random string, useful to create random passwords

Generating a Random String With Upper Case, Lower Case, Digits and Punctuation

The string module comes with a nice set of constants that we can combine with the random module to create our random string.

Using Python's string.ascii_letters + string.digits + string.punctuation Characters

By concatenating string.ascii_letters + string.digits + string.punctuation, we will have our pool of characters that we can pick at random using the random.choices() method. This method returns a k sized list of elements chosen from the population with replacement. In our case, k will be the size of our random string.

>>> import string

>>> string.ascii_letters

>>> string.digits

>>> string.punctuation

>>> all_chars = string.ascii_letters + string.digits + string.punctuation

>>> import random

>>> ''.join(random.choices(all_chars, k=10))

This works well, but there is one limitation: random.choices is available only on Python 3.6+. To make that work in older versions, you'll need to call the random.choice function and iterate over k times.

>>> ''.join((random.choice(all_chars) for _ in range(10)))

How to Generate a Cryptographically Secure Random String

The previous method works well if all we want is a random string for simple use cases. If what we want is a random string to be used as a password, then we need a more secure method. The reason is that the random module does not use a secure pseudo-number generator.

As an alternative we must resort to the Operating System’s pseudo-random number generator. The good news is that Python can access that using the random.SystemRandom class, which ensures that sequences are not reproducible.

We can re-use the previous example and change just one minor detail.

From: random.choices to random.SystemRandom()

>>> all_chars = string.ascii_letters + string.digits + string.punctuation

>>> import random

>>> ''.join(random.SystemRandom().choices(all_chars, k=10))


In this post we saw 2 different ways of creating random strings Python. I hope you find it useful.

Other posts you may like:

See you next time!

This post was originally published at