Answer in one line:

''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(N))

or even shorter starting with Python 3.6 using random.choices():

''.join(random.choices(string.ascii_uppercase + string.digits, k=N))

A cryptographically more secure version: see this post

''.join(random.SystemRandom().choice(string.ascii_uppercase + string.digits) for _ in range(N))

In details, with a clean function for further reuse:

>>> import string
>>> import random
>>> def id_generator(size=6, chars=string.ascii_uppercase + string.digits):
...    return ''.join(random.choice(chars) for _ in range(size))
...
>>> id_generator()
'G5G74W'
>>> id_generator(3, "6793YUIO")
'Y3U'

How does it work ?

We import string, a module that contains sequences of common ASCII characters, and random, a module that deals with random generation.

string.ascii_uppercase + string.digits just concatenates the list of characters representing uppercase ASCII chars and digits:

>>> string.ascii_uppercase
'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
>>> string.digits
'0123456789'
>>> string.ascii_uppercase + string.digits
'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'

Then we use a list comprehension to create a list of 'n' elements:

>>> range(4) # range create a list of 'n' numbers
[0, 1, 2, 3]
>>> ['elem' for _ in range(4)] # we use range to create 4 times 'elem'
['elem', 'elem', 'elem', 'elem']

In the example above, we use [ to create the list, but we don't in the id_generator function so Python doesn't create the list in memory, but generates the elements on the fly, one by one (more about this here).

Instead of asking to create 'n' times the string elem, we will ask Python to create 'n' times a random character, picked from a sequence of characters:

>>> random.choice("abcde")
'a'
>>> random.choice("abcde")
'd'
>>> random.choice("abcde")
'b'

Therefore random.choice(chars) for _ in range(size) really is creating a sequence of size characters. Characters that are randomly picked from chars:

>>> [random.choice('abcde') for _ in range(3)]
['a', 'b', 'b']
>>> [random.choice('abcde') for _ in range(3)]
['e', 'b', 'e']
>>> [random.choice('abcde') for _ in range(3)]
['d', 'a', 'c']

Then we just join them with an empty string so the sequence becomes a string:

>>> ''.join(['a', 'b', 'b'])
'abb'
>>> [random.choice('abcde') for _ in range(3)]
['d', 'c', 'b']
>>> ''.join(random.choice('abcde') for _ in range(3))
'dac'
Answer from Ignacio Vazquez-Abrams on Stack Overflow
๐ŸŒ
Compucademy
compucademy.net โ€บ python-random-string-generator
Python Random String Generator โ€“ Compucademy
Here is a simple function that generates a random string of a given length using Pythonโ€™s random and string modules.
Price ย  $$
Call ย  +44 7717 252766
Address ย  United Kingdom
Top answer
1 of 16
3307

Answer in one line:

''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(N))

or even shorter starting with Python 3.6 using random.choices():

''.join(random.choices(string.ascii_uppercase + string.digits, k=N))

A cryptographically more secure version: see this post

''.join(random.SystemRandom().choice(string.ascii_uppercase + string.digits) for _ in range(N))

In details, with a clean function for further reuse:

>>> import string
>>> import random
>>> def id_generator(size=6, chars=string.ascii_uppercase + string.digits):
...    return ''.join(random.choice(chars) for _ in range(size))
...
>>> id_generator()
'G5G74W'
>>> id_generator(3, "6793YUIO")
'Y3U'

How does it work ?

We import string, a module that contains sequences of common ASCII characters, and random, a module that deals with random generation.

string.ascii_uppercase + string.digits just concatenates the list of characters representing uppercase ASCII chars and digits:

>>> string.ascii_uppercase
'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
>>> string.digits
'0123456789'
>>> string.ascii_uppercase + string.digits
'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'

Then we use a list comprehension to create a list of 'n' elements:

>>> range(4) # range create a list of 'n' numbers
[0, 1, 2, 3]
>>> ['elem' for _ in range(4)] # we use range to create 4 times 'elem'
['elem', 'elem', 'elem', 'elem']

In the example above, we use [ to create the list, but we don't in the id_generator function so Python doesn't create the list in memory, but generates the elements on the fly, one by one (more about this here).

Instead of asking to create 'n' times the string elem, we will ask Python to create 'n' times a random character, picked from a sequence of characters:

>>> random.choice("abcde")
'a'
>>> random.choice("abcde")
'd'
>>> random.choice("abcde")
'b'

Therefore random.choice(chars) for _ in range(size) really is creating a sequence of size characters. Characters that are randomly picked from chars:

>>> [random.choice('abcde') for _ in range(3)]
['a', 'b', 'b']
>>> [random.choice('abcde') for _ in range(3)]
['e', 'b', 'e']
>>> [random.choice('abcde') for _ in range(3)]
['d', 'a', 'c']

Then we just join them with an empty string so the sequence becomes a string:

>>> ''.join(['a', 'b', 'b'])
'abb'
>>> [random.choice('abcde') for _ in range(3)]
['d', 'c', 'b']
>>> ''.join(random.choice('abcde') for _ in range(3))
'dac'
2 of 16
658

This Stack Overflow quesion is the current top Google result for "random string Python". The current top answer is:

''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(N))

This is an excellent method, but the PRNG in random is not cryptographically secure. I assume many people researching this question will want to generate random strings for encryption or passwords. You can do this securely by making a small change in the above code:

''.join(random.SystemRandom().choice(string.ascii_uppercase + string.digits) for _ in range(N))

Using random.SystemRandom() instead of just random uses /dev/urandom on *nix machines and CryptGenRandom() in Windows. These are cryptographically secure PRNGs. Using random.choice instead of random.SystemRandom().choice in an application that requires a secure PRNG could be potentially devastating, and given the popularity of this question, I bet that mistake has been made many times already.

If you're using python3.6 or above, you can use the new secrets module as mentioned in MSeifert's answer:

''.join(secrets.choice(string.ascii_uppercase + string.digits) for _ in range(N))

The module docs also discuss convenient ways to generate secure tokens and best practices.

Discussions

How to Generate Random Strings in Python
helpful content More on reddit.com
๐ŸŒ r/pythontips
2
5
October 9, 2024
Python random string/text/code generator with fixed length and some characters - Stack Overflow
So, a few years ago I have found an exploit in the giftcard system at McDonalds. The basic point is by combining about 15-20 cards, and their codes, I got a point that 3rd and the 7th characters ar... More on stackoverflow.com
๐ŸŒ stackoverflow.com
randomness - How to generate a random string in Python for a mission-critical application - Cryptography Stack Exchange
I'm trying to figure something out, but it is difficult for me. I need to generate a fully random string in Python. My current function is attached below. I just want to know whether this is secure... More on crypto.stackexchange.com
๐ŸŒ crypto.stackexchange.com
July 24, 2021
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
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ python-generate-random-string-of-given-length
Python - Generate Random String of given Length - GeeksforGeeks
July 11, 2025 - Slicing ensures the string matches the required length. The os.urandom function generates secure random bytes, which can be converted to a readable string.
๐ŸŒ
LabEx
labex.io โ€บ tutorials โ€บ python-how-to-generate-random-strings-quickly-418943
How to generate random strings quickly | LabEx
This comprehensive tutorial explores multiple techniques and best practices for efficiently creating random strings in Python, providing developers with practical strategies to generate randomized text quickly and effectively.
๐ŸŒ
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

Find elsewhere
๐ŸŒ
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 - โœ… Basic random string generation using random.choice() and list comprehensions โœ… Character pools using Python's string module โœ… Reusable functions for common use cases โœ… Validation for stronger password requirements โœ… Security considerations using secrets module
Top answer
1 of 3
1

You're almost there. I've just tweaked it a little - you could adjust it as is:

import random

numcount = 5
fstring = ""
length_of_code_you_want = 12
position_to_keep_constant_1 = 2 # first position to keep constant is position 3, index 2
position_to_keep_constant_2 = 6 # 2nd position to keep constant is position 7, index 6
constant_1 = "J" # the value of the constant at position 3
constant_2 = "L" # the value of the constant at position 7

for num in range(length_of_code_you_want): #strings are 19 characters long
    if random.randint(0, 1) == 1:
        x = random.randint(1, 8)
        x += 96
        fstring += (chr(x).upper())
    elif not numcount == 0:
        x = random.randint(0, 9)
        fstring += str(x)
        numcount -= 1

list_out = list(fstring)
list_out[position_to_keep_constant_1] = str(constant_1)
list_out[position_to_keep_constant_2] = str(constant_2)
string_out = "".join(list_out)
print(string_out)
2 of 3
1

Not sure about the legality of that, but the problem is easy enough.

import random
import string

value_of_seven = 7
value_of_three = 3

def randomString(stringLength=10):
    """Generate a random string of fixed length """
    letters = string.ascii_lowercase
    _string = ''.join(random.choice(letters) for i in range(stringLength))
    print ("Random String is ", randomString() )
    return _string

x = 0
string_set = set()
while x <= 10:
    x += 1
    rand_str = randomString()
    if rand_str[-1, 3] is value_of_seven and rand_str[1, 3] is value_of_three:
        string_set.add(rand_str)

But we really need to know, just letters lower case? Upper case?

Also if your trying to generate them with the same things in those places you would still slice at the same point and add the string on the end.

Ok here is working version with your requirements

import random
import string

value_of_seven = '7'
value_of_three = '3'


def _random(stringLength=5):
    """Generate a  string of Ch/digits """
    lett_dig = string.ascii_letters + string.digits
    return ''.join(random.choice(lett_dig) for i in range(stringLength))


if __name__ == '__main__':
    s = _random()
    s = s[:2] + value_of_three + s[2:]
    s = s[:6] + value_of_seven + s[6:]
    print(s)
๐ŸŒ
Educative
educative.io โ€บ answers โ€บ how-to-generate-a-random-string-in-python
How to generate a random string in Python
random.choice() is used to generate strings in which characters may repeat, while random.sample() is used for non-repeating characters.
๐ŸŒ
Squash
squash.io โ€บ how-to-generate-random-strings-with-upper-case-letters-and-digits-in-python
Creating Random Strings with Letters & Digits in Python
October 14, 2023 - To generate random strings with upper case letters and digits in Python, you can use the random module along with the string module.
๐ŸŒ
Cach3
tutorialspoint.com.cach3.com โ€บ generating-random-strings-until-a-given-string-is-generated-using-python.html
Generating random strings until a given string is generated using Python
November 8, 2018 - import string import random import time my_possibleCharacters = string.ascii_lowercase + string.digits + string.ascii_uppercase + ' ., !?;:' t = "ab" my_attemptThis = ''.join(random.choice(my_possibleCharacters) for i in range(len(t))) my_attemptNext = '' com = False iteration = 0 # Iterate while completed is false while com == False: print(my_attemptThis) my_attemptNext = '' com = True for i in range(len(t)): if my_attemptThis[i] != t[i]: com = False my_attemptNext += random.choice(my_possibleCharacters) else: my_attemptNext += t[i] # increment the iteration iteration += 1 my_attemptThis = my_attemptNext time.sleep(0.1) # Driver Code print("String matched after " + str(iteration) + " iterations")
๐ŸŒ
Python documentation
docs.python.org โ€บ 3 โ€บ library โ€บ random.html
random โ€” Generate pseudo-random numbers
1 month ago - Print a random floating-point number between 0 and N inclusive, using uniform(). If no options are given, the output depends on the input: String or multiple: same as --choice.
๐ŸŒ
Miguendes
miguendes.me โ€บ how-to-implement-a-random-string-generator-with-python
How to Implement a Random String Generator With Python
April 3, 2021 - In this post, you'll learn how to create a random string in Python using different methods; but, beware! Some of them only work with Python 3.6+. By the end of this article, you should be able to: use the choice function to generate a random string from string.ascii_letters, string.digits + string.punctuation characters in Python 3
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ generate-random-string-without-duplicates-in-python
Generate Random String Without Duplicates in Python - GeeksforGeeks
July 23, 2025 - import random import string # Generate a random string of 8 unique characters def generate_random_string(length): return ''.join(random.sample(string.ascii_letters, length)) random_string = generate_random_string(8) print(random_string)
๐ŸŒ
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 - The Python string generates a sequence of letters and numbers that can repeat the string in any order using the random.choices() method. Multiple random elements from the list with replacement are returned by the choices() method.
๐ŸŒ
MDN Web Docs
developer.mozilla.org โ€บ en-US โ€บ docs โ€บ Web โ€บ JavaScript โ€บ Reference โ€บ Global_Objects โ€บ Math โ€บ random
Math.random() - JavaScript | MDN
The Math.random() static method returns a floating-point, pseudo-random number that's greater than or equal to 0 and less than 1, with approximately uniform distribution over that range โ€” which you can then scale to your desired range. The implementation selects the initial seed to the random ...
๐ŸŒ
Readthedocs
python-string-utils.readthedocs.io โ€บ en โ€บ latest โ€บ generation.html
String Generation โ€” Python String Utils 1.0.0 documentation
Generated an UUID string (using uuid.uuid4()). ... >>> uuid() # possible output: '97e3a716-6b33-4ab9-9bb1-8128cb24d76b' >>> uuid(as_hex=True) # possible output: '97e3a7166b334ab99bb18128cb24d76b' ... as_hex โ€“ True to return the hex value of the UUID, False to get its default representation (default). ... Returns a string of the specified size containing random characters (uppercase/lowercase ascii letters and digits).
๐ŸŒ
Quora
quora.com โ€บ How-do-I-generate-a-random-string
How to generate a random string - Quora
Answer (1 of 6): How do I generate a random string? Your question leads to some other questions. Do you want the length of your random strings to be fixed or should the length itself be random? If the length should be random what is the maximum size string you want to allow? What character set d...