How to Implement a Random String Generator With Python

Subscribe to my newsletter and never miss my upcoming articles

Listen to this article

In this post, you'll learn how to generate a random string in python in two different ways. Some of these will only work on Python 3.6+.

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

The string module comes with a nice set of constants. We can then combine them with the random module to create our random string.

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)))

Generating a Cryptographically Secure 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.

If you liked this post, consider sharing it with your friends or buying me a coffee:)


Other posts you may like:

See you next time!

Comments (1)

Paula Maranhão's photo

Great! Now, I'm gonna have my own password generator!