CODE:

from random import choice
from string import ascii_uppercase

print(''.join(choice(ascii_uppercase) for i in range(12)))

OUTPUT:

5 examples:

QPUPZVVHUNSN
EFJACZEBYQEB
QBQJJEEOYTZY
EOJUSUEAJEEK
QWRWLIWDTDBD

EDIT:

If you need only digits, use the digits constant instead of the ascii_uppercase one from the string module.

3 examples:

229945986931
867348810313
618228923380
Answer from Peter Varo on Stack Overflow
Top answer
1 of 7
147

CODE:

from random import choice
from string import ascii_uppercase

print(''.join(choice(ascii_uppercase) for i in range(12)))

OUTPUT:

5 examples:

QPUPZVVHUNSN
EFJACZEBYQEB
QBQJJEEOYTZY
EOJUSUEAJEEK
QWRWLIWDTDBD

EDIT:

If you need only digits, use the digits constant instead of the ascii_uppercase one from the string module.

3 examples:

229945986931
867348810313
618228923380
2 of 7
26

By Django, you can use get_random_string function in django.utils.crypto module.

get_random_string(length=12,
    allowed_chars=u'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789')
    Returns a securely generated random string.

    The default length of 12 with the a-z, A-Z, 0-9 character set returns
    a 71-bit value. log_2((26+26+10)^12) =~ 71 bits

Example:

get_random_string()
u'ngccjtxvvmr9'

get_random_string(4, allowed_chars='bqDE56')
u'DDD6'

But if you don't want to have Django, here is independent code of it:

Code:

import random
import hashlib
import time

SECRET_KEY = 'PUT A RANDOM KEY WITH 50 CHARACTERS LENGTH HERE !!'

try:
    random = random.SystemRandom()
    using_sysrandom = True
except NotImplementedError:
    import warnings
    warnings.warn('A secure pseudo-random number generator is not available '
                  'on your system. Falling back to Mersenne Twister.')
    using_sysrandom = False


def get_random_string(length=12,
                      allowed_chars='abcdefghijklmnopqrstuvwxyz'
                                    'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'):
    """
    Returns a securely generated random string.

    The default length of 12 with the a-z, A-Z, 0-9 character set returns
    a 71-bit value. log_2((26+26+10)^12) =~ 71 bits
    """
    if not using_sysrandom:
        # This is ugly, and a hack, but it makes things better than
        # the alternative of predictability. This re-seeds the PRNG
        # using a value that is hard for an attacker to predict, every
        # time a random string is required. This may change the
        # properties of the chosen random sequence slightly, but this
        # is better than absolute predictability.
        random.seed(
            hashlib.sha256(
                ("%s%s%s" % (
                    random.getstate(),
                    time.time(),
                    SECRET_KEY)).encode('utf-8')
            ).digest())
    return ''.join(random.choice(allowed_chars) for i in range(length))
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-generate-random-string-of-given-length
Python - Generate Random String of given Length - GeeksforGeeks
July 11, 2025 - The list comprehension iterates for the desired length to build the string. This method is ideal for generating passwords or secure tokens. The uuid module can generate universally unique identifiers (UUIDs), which can be trimmed to a desired length. ... import uuid length = 8 random_string = str(uuid.uuid4()).replace('-', '')[:length] print(random_string)
Discussions

How do I generate a random string (of length X, a-z only) in Python? - Stack Overflow
Possible Duplicate: python random string generation with upper case letters and digits How do I generate a String of length X a-z in Python? More on stackoverflow.com
🌐 stackoverflow.com
How to Generate Random Strings in Python
helpful content More on reddit.com
🌐 r/pythontips
2
5
October 9, 2024
python - How to generate random strings that have variable length - Stack Overflow
I wanted to know how to print a random string in Python. I want this to be a random string like "ayhbygb", and be a random amount of letters long. So like, one time it could print "a", the next time it could print "aiubfiub", or "aiuhiu", etc. ... This is not a duplicate from the question it's marked as a duplicate of. Hugh Chalmers is asking for variable length ... More on stackoverflow.com
🌐 stackoverflow.com
how can i generate random strings of specific length?
What have you tried? We will help you if you are stuck but we will not write code for you. Hint: use random.choice in a loop. More on reddit.com
🌐 r/learnpython
11
2
June 6, 2018
🌐
PYnative
pynative.com › home › python › random › generate random strings and passwords in python
Generate Random Strings and Passwords in Python
February 16, 2022 - I basically understood, even though I’m a beginner in python. I figured this out myself, I emptied more things, it may not make much sense, but suddenly it popped out of my head when analyzing the scripts: (Many strings are separate because I didn’t need a value of 0.) 🙂 · import secrets import random import string for i in range(10): def get_random_string(length): # choose from all letter and number letters = string.ascii_lowercase upperc = string.ascii_uppercase numbers = '123456789' result_str1 = ''.join(random.choice(letters + upperc + numbers) for i in range(length)) result_str =
🌐
Python Examples
pythonexamples.org › python-generate-random-string-of-specific-length
Generate Random String of Specific Length - Python Examples
To generate a random string of specific length, follow these steps: Choose Character Group, use random.choice(), pick N characters and join them. Random string is generated.
🌐
DEV Community
dev.to › itsmycode › how-to-generate-a-random-string-of-a-given-length-in-python-54i1
How to Generate a random string of a given length in Python? - DEV Community
September 11, 2021 - If you don’t want to repeat the characters, then use random.sample() method. If you are looking for a secure and robust password, Python has a module called as secrets , and you could utilize this to generate a random secured password.
🌐
TutorialsPoint
tutorialspoint.com › article › python-generate-random-string-of-given-length
Python Generate random string of given length
3 weeks ago - import string import random # Length of string needed N = 8 # Using SystemRandom for cryptographic use secure_random = random.SystemRandom() characters = string.ascii_letters + string.digits + string.punctuation res = ''.join(secure_random....
Find elsewhere
🌐
Quora
quora.com › How-do-I-generate-a-random-string-of-length-n-with-a-specific-number-of-letters-and-a-specific-number-of-numbers-as-well-in-Python
How to generate a random string of length n with a specific number of letters and a specific number of numbers as well in Python - Quora
To generate a random string of ... Python, choose the character sets, sample the desired counts without replacement from each set (or with replacement if characters can repeat), then shuffle the combined list and join to a string...
🌐
Reddit
reddit.com › r/pythontips › how to generate random strings in python
r/pythontips on Reddit: How to Generate Random Strings in Python
October 9, 2024 -

Hi Python programmers, here we are see How to Generate Random Strings in Python with the help of multiple Python modules and along with multiple examples.

In many programming scenarios, generating random strings is a common requirement. Whether you’re developing a password generator, creating test data, or implementing randomized algorithms, having the ability to generate random strings efficiently is essential. Thankfully, Python offers several approaches to accomplish this task easily. In this article, we’ll explore various methods and libraries available in Python for generating random strings.

  1. Using the random Module

The random module in Python provides functions for generating random numbers, which can be utilized to create random strings. Here’s a basic example of how to generate a random string of a specified length using random.choice()

import random
import string

def generate_random_strings(length):
    return ''.join(random.choice(string.ascii_letters + string.digits) for _ in range(length))

# Example usage:
random_string = generate_random_strings(10)
print("Random String:", random_string)

2. Using the Secrets Module

For cryptographic purposes or when higher security is required, it’s recommended to use the secrets module, introduced in Python 3.6. This Python built-in module provides functionality to generate secure random numbers and strings. Here’s how you can generate a random string using secrets.choice()

import secrets
import string


def generate_random_string(length):
    return ''.join(secrets.choice(string.ascii_letters + string.digits) for _ in range(length))


# Example usage:
random_string = generate_random_string(10)
print("Random String:", random_string)

This is how you can generate random Python strings for your applications.

I have written a complete article on this click here to read.

Thanks

🌐
Flexiple
flexiple.com › python › generate-random-string-python
How to generate a random string in Python? - Flexiple
The secret methods do not have a .choices method which takes a second argument. Hence we use a loop and get the range to the number of characters. Both methods can be used to generate a random string in Python.
🌐
DEV Community
dev.to › outdated-dev › generate-random-strings-with-python-a-quick-guide-1nfm
Generate Random Strings with Python: A Quick Guide - DEV Community
December 24, 2025 - Args: length: Desired string length ... uppercase letters by setting min_uppercase=0 print(generate_random_string(length=12, min_uppercase=0)) >>> 'abc123def456' Generating random strings in Python is straightforward once you understand the basics!...
🌐
Javatpoint
javatpoint.com › python-program-to-generate-a-random-string
Python Program to generate a Random String - Javatpoint
Python Program to generate a Random String with python, tutorial, tkinter, button, overview, entry, checkbutton, canvas, frame, environment set-up, first python program, basics, operators, etc.
🌐
Stack Abuse
stackabuse.com › how-to-generate-random-strings-in-python
How to Generate Random Strings in Python
June 27, 2023 - We'll first define a function generate_random_string that takes an argument length representing the desired length of the random string. It will combine all available characters (letters, digits, and punctuation) and then generate a random string of the specified length using a list comprehension ...
🌐
Testmuai
testmuai.com › testmu ai › blog › how to use python for random string generation | testmu ai
How To Use Python For Random String Generation | TestMu AI (Formerly LambdaTest)
December 24, 2025 - import random import string min_length = 8 max_length = 12 length = random.randint(min_length, max_length) str_characters = string.ascii_letters + string.digits + "!@#$%^&*" generated_string = ''.join(random.choice(str_characters) for _ in ...
🌐
Educative
educative.io › answers › how-to-generate-a-random-string-in-python
How to generate a random string in Python
A random string can be generated in Python by using the built-in random and string libraries.
🌐
ContextQA
contextqa.com › home › how to use python for random string generation
How To Use Python For Random String Generation | Best Guide
November 25, 2024 - Learn to use Python for random string generation - various software development tasks, including password generation, database testing & security.
🌐
AskPython
askpython.com › home › how to generate random strings in python
How to Generate Random Strings in Python - AskPython
February 16, 2023 - We’ll then use the random.choice() method to randomly choose characters, instead of using integers, as we did previously. Let us define a function random_string_generator(), that does all this work for us. This will generate a random string, ...
🌐
GitHub
github.com › ljnath › PyRandomString
GitHub - ljnath/PyRandomString: Python library to generate N random strings of M length · GitHub
import PyRandomString py_random_string = PyRandomString.RandomString() ## calling method to get a single random string random_string = py_random_string.get_string(string_type=PyRandomString.StringType.ALPHA_NUMERIC_ALL_CASE, random_length=False, max_length=10) print('Single random string is {}'.format(random_string)) ## calling method to get a single random string with custom symbols random_string = py_random_string.get_string(string_type=PyRandomString.StringType.ALPHA_NUMERIC_ALL_CASE_WITH_SYMBOLS, random_length=False, max_length=10, symbols='+-*#$%^&') print('Single random string with custo
Author   ljnath