
In modern Python projects, random strings are commonly used for multifarious purposes, such as originating identifiers (IDs) for database records, making secure passwords or authentication tokens, uniquely naming files or folders to avoid conflicts, creating codes or coupons for promotions or discounts, etc. This pithy, example-based article will walk you through several different techniques to generate a random string in Python.
Using the “uuid” module
UUID stands for Universally Unique Identifier. It is a 128-bit number that can be used to identify objects across distributed systems.
uuid
is a built-in module of Python that provides immutable UUID objects (the UUID
class) and the functions uuid1()
, uuid3()
, uuid4()
, uuid5()
for generating version 1, 3, 4, and 5 UUIDs as specified in RFC 4122. You can take advantage of the uuid
module to generate random and unique strings by following the steps below:
- Import the
uuid
module - Use the
uuid.uuid4()
function to generate a random UUID - Convert the UUID to a string representation.
Example:
import uuid
# Generate a random UUID
random_uuid = uuid.uuid4()
# Convert the UUID to a string
random_string = str(random_uuid)
# Print the random string
print(random_string)
Output (this will change each time you re-execute the code):
f29c3d4a-f0ee-47f0-9456-b3f25401f57e
The generated random string is in the UUID format, which includes hyphens and follows a specific structure. If that is not what you want, just move on to the next section.
Using the “random” module and a custom character set
This approach is a five-step process:
- Import the
random
module. - Define a string of characters from which the random string will be generated.
- Use the
random.choices()
function to randomly select characters from the defined string. - Join the selected characters using the
join()
method. - Specify the length of the random string you want to generate.
A code example will help you understand better:
import random
import string
# Set the lenght of the random string
length = 20 # Change the value of this variable to your desired length
# Define the characters to choose from
characters = string.ascii_letters + string.digits
# Generate the random string
random_string = ''.join(random.choices(characters, k=length))
# Print the random string
print(random_string)
Output (yours might be different from mine due to the randomness):
JKKpszw8lKMbrUW4ulde
This approach allows customization of the character set from which the random string is generated. You can also control the length of the output. However, the generated random string isn’t guaranteed to be unique. If you want to create user IDs or something like that, see other solutions in this article.
Using the “secrets” module and a custom character set
This approach is similar to the preceding approach, but it is more secure since we will use the secrets
module instead of the random
module. You need Python 3.6 (which was released on December 23, 2016 – a long time ago) or above.
The steps are:
- Import the
secrets
module. - Use the
secrets.choice()
function to randomly select characters from a predefined character set. - Join the selected characters using the
join()
method. - Specify the length of the random string you want to produce.
Code implementation:
import secrets
# Set the desired length of the random string
length = 30
# Define the characters to choose from
characters = "abcdefghijklmnopqrstuvwxyz1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ!@#$%^&*()?"
# Generate the random string
random_string = ''.join(secrets.choice(characters) for _ in range(length))
# Print the random string
print(random_string)
Output (as always, the output is not a constant):
%EujA5COIZ4$SKOSFY^L2Eb1nqM#zm
Encrypting a random number
Using the “datetime” module and the “hashlib” module
Time never stops passing, and we can use the datetime
module and the hashlib
module to generate unique and unpredictable strings. Here’re how we do so:
- Import the
datetime
module and thehashlib
module. - Get the current date and time using
datetime.now()
. - Format the date and time into a string representation.
- Use a hashing algorithm from the
hashlib
module to encrypt the formatted date and time.
Code example:
import datetime
import hashlib
# Get the current date and time
current_datetime = datetime.datetime.now()
# Format the date and time
formatted_datetime = current_datetime.strftime('%Y%m%d%H%M%S%f')
# Encrypt the date time using a hashing algorithm
hash_object = hashlib.sha256(formatted_datetime.encode())
random_hash = hash_object.hexdigest()
# Print the random string
print(random_hash)
Output:
c08142fa52b690763b3b09911fde2f491e98ad14906cafcfa3f4771d470d44ec
The length of the generated random string may vary depending on the chosen hashing algorithm.