Last updated: Apr 10, 2024
Reading timeยท9 min
To generate a random alphanumeric string:
string
module to construct an alphanumeric string.random.choices()
module to get a list of random alphanumeric
characters.str.join()
method to join the list into a string.import random import string def random_alphanumeric_string(length): return ''.join( random.choices( string.ascii_letters + string.digits, k=length ) ) print(random_alphanumeric_string(10)) # ๐๏ธ daJVz1oSjG print(random_alphanumeric_string(15)) # ๐๏ธ JQ7e5h9AvEjRNSy
The string.ascii_letters attribute returns a string containing the uppercase and lowercase ASCII letters.
However, you can also use the ascii_uppercase
or ascii_lowercase
attributes.
The
string.ascii_uppercase
attribute returns a string containing the uppercase letters from A
to Z
.
The
string.ascii_lowercase
attribute returns a string containing the lowercase letters from a
to z
.
# ๐๏ธ abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ print(string.ascii_letters) print(string.ascii_lowercase) # ๐๏ธ abcdefghijklmnopqrstuvwxyz print(string.ascii_uppercase) # ๐๏ธ ABCDEFGHIJKLMNOPQRSTUVWXYZ print(string.digits) # ๐๏ธ 0123456789
The
string.digits()
method returns a string of the digits from 0
to 9
.
random.choice()
method in older Python versionsThe random.choices()
method was introduced in Python v3.6. If you use an older
version, use the random.choice()
method instead.
import string import random def random_alphanumeric_string(length): return ''.join( random.choice(string.ascii_lowercase + string.digits) for _ in range(length) ) print(random_alphanumeric_string(10)) # ๐๏ธ ydc2299u79 print(random_alphanumeric_string(15)) # ๐๏ธ ydc2299u79
The newer
random.choices()
method takes a sequence and a k
keyword argument and returns a k
sized list
of elements chosen from the sequence.
import string import random # ๐๏ธ ['D', 'x', 't', 's', 'c', 'J', 'w', 'E', 'Z', 'N', 'W', 'c', '2', 'U', 'L'] print( random.choices( string.ascii_letters + string.digits, k=15 ) )
Once we have a list of random characters and digits, we can use the str.join()
method to join the list into a string.
import string import random # ๐๏ธ KRzHdlqbBJl6d4N print( ''.join( random.choices( string.ascii_letters + string.digits, k=15 ) ) )
The str.join() method takes an iterable as an argument and returns a string which is the concatenation of the strings in the iterable.
The string the method is called on is used as the separator between the elements.
The older random.choice() method takes a sequence and returns a random element from the non-empty sequence.
import string import random # ๐๏ธ S0HCXICBgJ print( ''.join( random.choice( string.ascii_letters + string.digits ) for _ in range(10) ) )
We used a
generator expression
to iterate over a range
object of length N.
The range() class is commonly used for looping a specific number of times.
print(list(range(2))) # ๐๏ธ [0, 1] print(list(range(3))) # ๐๏ธ [0, 1, 2]
If you need to generate a cryptographically secure alphanumeric string, use the
built-in secrets
module.
This is a three-step process:
string
module to construct an alphanumeric string.secrets.choice()
method to pick N random letters and numbers.str.join()
method to join the list into a string.import string import secrets def random_alphanumeric_string(length): return ''.join( secrets.choice(string.ascii_letters + string.digits) for _ in range(length) ) print(random_alphanumeric_string(10)) # ๐๏ธ JI5NndixNT print(random_alphanumeric_string(15)) # ๐๏ธ yFgd7m7ZbxQOM18
The secrets module is used for generating cryptographically strong random numbers for passwords, security tokens, etc.
This should be your preferred approach if you need to generate random numbers used for managing passwords and security tokens.
We used a generator expression to iterate over a range
object of length N.
We used an underscore _
for the name of the variable. There is a convention to
use an underscore as the name of placeholder variables we don't intend to use.
On each iteration, we pick a random letter or digit from the string and return the result.
The last step is to join the generator
object into a string.
Alternatively, you can use the built-in uuid
module.
This is a three-step process:
uuid.uuid4()
method to generate a random ID with numbers and
letters.str.replace()
method to remove the hyphens from the ID.import uuid def gen_random_string(length): return str(uuid.uuid4()).replace('-', '')[:length] print(gen_random_string(10)) # ๐๏ธ 54310d3e9b print(gen_random_string(15)) # ๐๏ธ ae4a22bac9484e3 print(gen_random_string(10).upper()) # ๐๏ธ F5C2523DD8
The built-in uuid
module provides immutable UUID
objects and functions for generating UUIDs.
The uuid.uuid4() method is the most commonly used approach to generate random IDs in Python.
import uuid print(uuid.uuid4()) # ๐๏ธ bfd19cc4-3dc8-4266-a04f-1cb0aa38fc3b print(uuid.uuid4()) # ๐๏ธ c6c43d56-57b7-4f77-9156-32155779e978
We used the str() class to convert the
UUID
object to a string and used the str.replace()
method to remove the
hyphens.
The str.replace() method returns a copy of the string with all occurrences of a substring replaced by the provided replacement.
The method takes the following parameters:
Name | Description |
---|---|
old | The substring we want to replace in the string |
new | The replacement for each occurrence of old |
count | Only the first count occurrences are replaced (optional) |
import uuid def gen_random_string(length): return str(uuid.uuid4()).replace('-', '')[:length]
The last step is to use string slicing to get a random string of length N with numbers and letters.
The syntax for string slicing
is my_str[start:stop:step]
.
The start
index is inclusive, whereas the stop
index is exclusive (up to,
but not including).
If the start
index is omitted, it is considered to be 0
, if the stop
index
is omitted, the slice goes to the end of the string.
To generate a random string with special characters:
string
module to get a string of special characters, letters and
digits.random.choices()
method to get a list of random characters.str.join()
method to join the list into a string.import random import string def string_with_special_chars(length): return ''.join( random.choices( string.ascii_lowercase + string.digits + string.punctuation, k=length ) ) print(string_with_special_chars(8)) # ๐๏ธ |(@)ybq| print(string_with_special_chars(6)) # ๐๏ธ y`1qq:
We used the string module to construct a string of special characters, letters and digits.
The string.punctuation attribute returns a string of punctuation characters.
import string print(string.punctuation) # ๐๏ธ !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~ print(string.ascii_lowercase) # ๐๏ธ abcdefghijklmnopqrstuvwxyz print(string.ascii_uppercase) # ๐๏ธ ABCDEFGHIJKLMNOPQRSTUVWXYZ print(string.digits) # ๐๏ธ 0123456789
The random.choices()
method was introduced in Python 3.6. If you use an older
version, use the random.choice()
method instead.
import string import random def string_with_special_chars(length): return ''.join( random.choice(string.ascii_lowercase + string.digits + string.punctuation) for _ in range(length) ) print(string_with_special_chars(8)) # ๐๏ธ g`t:1cg0 print(string_with_special_chars(6)) # ๐๏ธ ~n#h.m
The newer
random.choices
method takes a sequence and a k
keyword argument and returns a k
sized list
of elements chosen from the sequence.
import string import random # ๐๏ธ ['z', 'o', 'v', 'o', '>', 'w', 's', '`', 'n', '>'] print( random.choices( string.ascii_lowercase + string.digits + string.punctuation, k=10 ) )
Once we have a list of random characters and digits, we can use the str.join()
method to join the list into a string.
import string import random def string_with_special_chars(length): return ''.join( random.choices( string.ascii_lowercase + string.digits + string.punctuation, k=length ) ) print(string_with_special_chars(8)) # ๐๏ธ g`t:1cg0 print(string_with_special_chars(6)) # ๐๏ธ ~n#h.m
The str.join method takes an iterable as an argument and returns a string which is the concatenation of the strings in the iterable.
The string the method is called on is used as the separator between the elements.
The older random.choice() method takes a sequence and returns a random element from the non-empty sequence.
import random # ๐๏ธ y print(random.choice('bobbyhadz'))
If you need to generate a cryptographically secure random string with special
characters, use the secrets
module.
This is a three-step process:
string
module to get a string of special characters, letters and
digits.secrets.choice()
method to get N random characters from the string.str.join()
method to join the collection into a string.import string import secrets def string_with_special_chars(length): return ''.join( secrets.choice(string.ascii_lowercase + string.digits + string.punctuation) for _ in range(length) ) print(string_with_special_chars(8)) # ๐๏ธ 8o}^^$i> print(string_with_special_chars(6)) # ๐๏ธ w8z"^i
The secrets module is used for generating cryptographically strong random numbers for passwords, security tokens, etc.
This should be your preferred approach if you need to generate random numbers used for managing passwords and security tokens.
range
object and generated N random special characters, letters and digits.Generator expressions are used to perform some operation for every element or select a subset of elements that meet a condition.
The last step is to use the str.join()
method to join the generator object
into a string.
Use the uuid.uuid4()
method to generate unique IDs.
The uuid
built-in module implements a uuid4()
method that generates and
returns a random ID.
import uuid print(uuid.uuid4()) # ๐๏ธ 730ed4ba-d703-4cdf-8b30-f8399352fabb print(uuid.uuid4().int) # ๐๏ธ 136047018022410445780946091752650147825 print(uuid.uuid4().bytes) # ๐๏ธ b'*\xe1h**\xceC\x87\xae\x8e\x1d\x81zX\x1c\xef' print(uuid.uuid4().hex) # ๐๏ธ 4fa066987b2c4507a949a94c1fb43f50
We used the uuid.uuid4 method to generate random IDs.
import uuid print(uuid.uuid4()) # ๐๏ธ 730ed4ba-d703-4cdf-8b30-f8399352fabb print(uuid.uuid4()) # ๐๏ธ 81fd808b-76a0-4ebf-9096-f45d6f7d495a print(uuid.uuid4()) # ๐๏ธ 753237da-bb2e-460a-88bb-329cc1dc5fe4
The built-in uuid
module provides immutable UUID
objects and functions for generating UUIDs.
uuid4()
method.You can pass the unique ID to the str() class to convert the UUID to a string of hex digits in standard form.
import uuid unique_id = uuid.uuid4() print(unique_id) # ๐๏ธ 011963c3-7fa3-4963-8599-a302f9aefe7d print(type(unique_id)) # ๐๏ธ <class 'uuid.UUID'> unique_id_str = str(unique_id) print(unique_id_str) # ๐๏ธ 011963c3-7fa3-4963-8599-a302f9aefe7d print(type(unique_id_str)) # ๐๏ธ <class 'str'>
You can access the bytes
attribute of the UUID object to get the raw 16 bytes
of the UUID.
import uuid unique_id_bytes = uuid.uuid4().bytes print(unique_id_bytes) # ๐๏ธ b'\x9e\xfb\xf4Ma\xc1I\xcc\xa0[2\\\xb6\xe9\x06\x9f' # ๐๏ธ generate UUID from 16-byte string result = uuid.UUID(bytes=unique_id_bytes) print(result) # ๐๏ธ 9efbf44d-61c1-49cc-a05b-325cb6e9069f
The int
attribute of the UUID object returns the UUID as a 128-bit integer.
import uuid unique_id_int = uuid.uuid4().int print(unique_id_int) # ๐๏ธ 49084253960468019865244738914988538494
The hex
attribute of the object returns the UUID as a 32-character lowercase
hexadecimal string.
import uuid unique_id_int = uuid.uuid4().hex print(unique_id_int) # ๐๏ธ c56fb2e760fb4d3ba6c426c00c602a55
uuid.uuid4()
methodIf all you need is a random ID, use the uuid.uuid4()
method.
import uuid random_unique_id = uuid.uuid4() print(random_unique_id) # ๐๏ธ 1fafff7f-6248-41f0-8b28-1e28bb12962b
You can also use the uuid.uuid4()
method to generate random file names.
import uuid file_name = str(uuid.uuid4()) print(file_name) # ๐๏ธ 6940556e-86cc-48d5-ac72-79913cb73733 file_name = uuid.uuid4().hex print(file_name) # ๐๏ธ 91abcd2405ff4b1dbd91b6cdf03c38fe
We used the uuid.uuid4 method to generate random file names.
import uuid file_name = str(uuid.uuid4()) print(file_name) # ๐๏ธ 6940556e-86cc-48d5-ac72-79913cb73733 file_name = str(uuid.uuid4()) print(file_name) # ๐๏ธ 27970c33-0eb0-46ae-9c3e-cc03d6b3ab79 file_name = str(uuid.uuid4()) print(file_name) # ๐๏ธ 9f2080a8-55c2-4f7b-8f14-ffcb5cea87e6
The built-in uuid
module provides immutable UUID
objects and functions for generating UUIDs.
str()
class to convert the UUID to a string of hex digits in standard form.If you don't want the file name to contain hyphens, use the hex
attribute on
the UUID
object.
import uuid file_name = uuid.uuid4().hex print(file_name) # ๐๏ธ 4208551e610744f182fbdec833aab7ca file_name = uuid.uuid4().hex print(file_name) # ๐๏ธ e5cfa690f9f1494a8bc709c5ca4d66ab file_name = uuid.uuid4().hex print(file_name) # ๐๏ธ 1459a8deddfb4cd5bd5cf39fc655ec12
The hex
attribute of the object returns the UUID as a 32-character lowercase
hexadecimal string.
If you need to generate a temporary file with a random name, use the tempfile
module.
The tempfile.NamedTemporaryFile
function generates a temporary file with a
random file name.
import tempfile file = tempfile.NamedTemporaryFile() print(file.name) # ๐๏ธ /tmp/tmpz8uy3ya4 file.close()
The tempfile.NamedTemporaryFile function returns a file-like object that can be used as a temporary storage area.
name
attribute on the object to access the file's name on the file system.By default, the file is deleted as soon as it is closed, but you can set the
delete
keyword argument to False
to keep the file.
import tempfile file = tempfile.NamedTemporaryFile(mode='w+b', delete=False) print(file.name) # ๐๏ธ /tmp/tmpz8uy3ya4 print(file.file) # ๐๏ธ <_io.BufferedRandom name='/tmp/tmp4oki5i7m'> file.close()
You can also set the optional prefix
and suffix
arguments if you need to
tweak the random file name.
import tempfile file = tempfile.NamedTemporaryFile(mode='w+b', delete=False, prefix='abc') print(file.name) # ๐๏ธ /tmp/abclogogxys print(file.file) # ๐๏ธ <_io.BufferedRandom name='/tmp/abclogogxys'> file.close()
The mode
parameter defaults to w+b
, so the file can be read and written
without being closed.
The w+b
mode opens the file for writing and reading in binary mode and
overwrites the existing file if it exists.
If the file doesn't exist, a new file with the given name is created.
Binary mode is used so that the function behaves consistently on all platforms regardless of the type of data that is stored.
You can learn more about the related topics by checking out the following tutorials: