Having to generate random strings in python is something that I’ve had to do more times than I can count, and in this blog post, I’m going to show you how to generate them with three different libraries that come out of the box with python.
Quick fix! If you are only looking for a simple function to generate random strings of a given length here is a code sample to do just that:
import string from random import choice def random_string(length: int) -> str: alphabet = string.ascii_letters + string.digits return ''.join(choice(alphabet) for _ in range(length)) random_string(10) # returns: 'qntZEHM9mI'
If you are still with me and want to learn more about randomness in Python here are the three libraries that we’ll be exploring here:
- uuid for strings between 1 and 36 characters of length.
- random for more custom results.
- secret for generating cryptographically strong strings.
UUID stands for “Universally Unique Identifiers”, and they are strings of 36 characters of length that are usually assigned to some piece of information that needs to be unique, as the name implies. Let’s say for example that you need to name the files that users can upload to your site, for that example you could use the following code:
import uuid str(uuid.uuid4()) # returns: 'f82459cb-ff36-4c95-b96c-213cc37bdc48'
As you can see with just 2 lines of code you can generate a random identifier that has a very little chance of being duplicated.
If you need less than 36 characters you can just truncate the str() function like this:
str(uuid.uuid4())[:10] # returns: 'c370e131-2'
Okey uuid is simple and all, but what if you need more than 36 characters or want to decide exactly what your resulting string is made of? In that case, what you need is the “choice” function from the random library.
The following example generates strings of 10 characters of length while only using “abc” as the substrings:
from random import choice ''.join(random.choice('abc') for _ in range(10)) # returns: 'aaabccccac'
Combining the “choice” function with others from the “string” library can give us the same result as the quick fix function presented at the beginning, or something like the following with all the printable characters:
import string ''.join(choice(string.printable) for _ in range(10)) # returns: '?hnXW^aO@^'
Always remember that the “choice” function can also take in lists, so the following code will be also correct:
''.join(choice(['lo','re','mi','ps','um']) for _ in range(10)) # returns: 'psmirepslomipsumlops'
For now we’v been showing methods for generating random strings, luckliy for numbers is much more easy, just import the “randint” function from random and give it two numbers as the starting and ending one. In this example we generate random numbers from 1000 to 9999, or in other words random numbers of length 4:
from random import randint randint(1000, 9999) # returns: 7087
Lastly, for generating cryptographically strong strings the “secrets” library can be used, but take into account that the methods generate strings with nbytes random bytes of length. Here is a simple example for generating a random token:
import secrets secrets.token_urlsafe() # returns: '-bMVVHxTeqqrYVJK_E5Z11xBaveSKfS-5825akbWido'
You can read more about the secrets library on the official python documentation.
You now know of three libraries that come with Python that allow you to generate all kinds of random elements, where you go from here is up to you, just remember that the secrets library is there for a reason and that it will be your best choice for generating passwords or API keys.Written with ❤️ by Victor Ciurana