Generate a random alphanumeric String in Python

avatar
Borislav Hadzhiev

Last updated: Apr 10, 2024
9 min

banner

# Table of Contents

  1. Generate a random alphanumeric string in Python
  2. Generate a random alphanumeric string using secrets.choice()
  3. Generate random string with numbers and letters using uuid
  4. Generate a random String with special characters in Python
  5. Generate a random String with special characters using secrets.choice()
  6. Generate unique IDs in Python
  7. Generate random file names in Python
  8. Generate a temporary file with a random file name

# Generate a random alphanumeric string in Python

To generate a random alphanumeric string:

  1. Use the string module to construct an alphanumeric string.
  2. Use the random.choices() module to get a list of random alphanumeric characters.
  3. Use the str.join() method to join the list into a string.
main.py
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

generate random alphanumeric string

The code for this article is available on GitHub

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.

main.py
# ๐Ÿ‘‡๏ธ 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.

# Using the random.choice() method in older Python versions

The random.choices() method was introduced in Python v3.6. If you use an older version, use the random.choice() method instead.

main.py
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

using the random choice method in older python versions

The code for this article is available on GitHub

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.

main.py
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.

main.py
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.

main.py
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.

main.py
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.

# Generate a random alphanumeric string using secrets.choice()

This is a three-step process:

  1. Use the string module to construct an alphanumeric string.
  2. Use the secrets.choice() method to pick N random letters and numbers.
  3. Use the str.join() method to join the list into a string.
main.py
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

generate random alphanumeric string using secrets module

The code for this article is available on GitHub

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.

Generator expressions are used to perform some operation for every element or select a subset of elements that meet a condition.

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.

# Generate random string with numbers and letters using uuid

This is a three-step process:

  1. Use the uuid.uuid4() method to generate a random ID with numbers and letters.
  2. Use the str.replace() method to remove the hyphens from the ID.
  3. Use string slicing to get a string of length N.
main.py
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 code for this article is available on GitHub

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.

main.py
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:

NameDescription
oldThe substring we want to replace in the string
newThe replacement for each occurrence of old
countOnly the first count occurrences are replaced (optional)
main.py
import uuid def gen_random_string(length): return str(uuid.uuid4()).replace('-', '')[:length]
We used an empty string for the replacement to remove all occurrences of a hyphen from the string.

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.

# Generate a random String with special characters in Python

To generate a random string with special characters:

  1. Use the string module to get a string of special characters, letters and digits.
  2. Use the random.choices() method to get a list of random characters.
  3. Use the str.join() method to join the list into a string.
main.py
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:
The code for this article is available on GitHub

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.

main.py
import string print(string.punctuation) # ๐Ÿ‘‰๏ธ !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~ print(string.ascii_lowercase) # ๐Ÿ‘‰๏ธ abcdefghijklmnopqrstuvwxyz print(string.ascii_uppercase) # ๐Ÿ‘‰๏ธ ABCDEFGHIJKLMNOPQRSTUVWXYZ print(string.digits) # ๐Ÿ‘‰๏ธ 0123456789

# Generate a random String with special characters using random.choice()

The random.choices() method was introduced in Python 3.6. If you use an older version, use the random.choice() method instead.

main.py
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.

main.py
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.

main.py
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.

main.py
import random # ๐Ÿ‘‡๏ธ y print(random.choice('bobbyhadz'))

If you need to generate a cryptographically secure random string with special characters, use the secrets module.

# Generate a random String with special characters using secrets.choice()

This is a three-step process:

  1. Use the string module to get a string of special characters, letters and digits.
  2. Use the secrets.choice() method to get N random characters from the string.
  3. Use the str.join() method to join the collection into a string.
main.py
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 code for this article is available on GitHub

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

# Generate unique IDs in Python

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.

main.py
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

generate unique ids in python

We used the uuid.uuid4 method to generate random IDs.

main.py
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.

If all you need is a unique ID, you should use the uuid4() method.

# Converting the UUID to a String of Hex digits

You can pass the unique ID to the str() class to convert the UUID to a string of hex digits in standard form.

main.py
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'>

converting the uuid to string of hex digits

The code for this article is available on GitHub

# Getting the raw 16 bytes of the UUID

You can access the bytes attribute of the UUID object to get the raw 16 bytes of the UUID.

main.py
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

# Converting the UUID to a 128-bit integer

The int attribute of the UUID object returns the UUID as a 128-bit integer.

main.py
import uuid unique_id_int = uuid.uuid4().int print(unique_id_int) # ๐Ÿ‘‰๏ธ 49084253960468019865244738914988538494

# Converting the UUID to a 32-character hexadecimal string

The hex attribute of the object returns the UUID as a 32-character lowercase hexadecimal string.

main.py
import uuid unique_id_int = uuid.uuid4().hex print(unique_id_int) # ๐Ÿ‘‰๏ธ c56fb2e760fb4d3ba6c426c00c602a55

# Getting a random ID with the uuid.uuid4() method

If all you need is a random ID, use the uuid.uuid4() method.

main.py
import uuid random_unique_id = uuid.uuid4() print(random_unique_id) # ๐Ÿ‘‰๏ธ 1fafff7f-6248-41f0-8b28-1e28bb12962b

# Generate random file names in Python

You can also use the uuid.uuid4() method to generate random file names.

main.py
import uuid file_name = str(uuid.uuid4()) print(file_name) # ๐Ÿ‘‰๏ธ 6940556e-86cc-48d5-ac72-79913cb73733 file_name = uuid.uuid4().hex print(file_name) # ๐Ÿ‘‰๏ธ 91abcd2405ff4b1dbd91b6cdf03c38fe
The code for this article is available on GitHub

We used the uuid.uuid4 method to generate random file names.

main.py
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.

You can pass the unique ID to the 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.

main.py
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.

The probability of generating a duplicate UUID is not zero, but it is close enough to zero to be negligible.

# Generate a temporary file with a random file name

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.

main.py
import tempfile file = tempfile.NamedTemporaryFile() print(file.name) # ๐Ÿ‘‰๏ธ /tmp/tmpz8uy3ya4 file.close()
The code for this article is available on GitHub

The tempfile.NamedTemporaryFile function returns a file-like object that can be used as a temporary storage area.

You can use the 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.

main.py
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.

main.py
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.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.

Copyright ยฉ 2024 Borislav Hadzhiev