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

🌐
Spark By {Examples}
sparkbyexamples.com › home › python › random string generation with letters and digits in python
Random String Generation with Letters and Digits in Python - Spark By {Examples}
May 31, 2024 - We can use the secrets.choice() function to randomly select characters from a string containing all uppercase letters and digits. # Random Numbers + Random Digits Generation import secrets import string # Function that take lenght is parameter ...
Discussions

[beginner]How do i generate a list of random letters?
I want to generate more than 1 letters at a time. Then you use a loop. Python is really good at loops. Either generate one character and add it to the list and repeat, or use a similar list comprehension. There are other ways to do this using the random module. Show us your code so we can make appropriate suggestions. More on reddit.com
🌐 r/learnpython
38
8
December 28, 2023
How to Generate Random Strings in Python
helpful content More on reddit.com
🌐 r/pythontips
2
5
October 9, 2024
How to generate random strings in Python? - Stack Overflow
How do you create a random string in Python? I need it to be number then character, repeating until the iteration is done. This is what I created: def random_id(length): number = '0123456789' More on stackoverflow.com
🌐 stackoverflow.com
Python code that makes a word with random numbers and character in last
I would write a little generator function for this.. import random from string import ascii_lowercase, ascii_uppercase, digits, punctuation, ascii_letters def wrdgen(stem="hrk"): def gen(): dandp = digits+punctuation a = random.choice(dandp) yield a b = random.choice(dandp) if a.isdigit() else random.choice(digits) yield b yield random.choice(punctuation) if f"{a}{b}".isdigit() else random.choice(digits) g = gen() return f"{stem}{next(g)}{next(g)}{next(g)}" print(wrdgen()) for _ in range(2): print(wrdgen("".join(random.choices(ascii_letters, k=3)))) print(wrdgen("".join(random.choices(ascii_uppercase, k=3)))) print(wrdgen("".join(random.choices(ascii_lowercase, k=3)))) More on reddit.com
🌐 r/learnpython
6
2
November 10, 2023
Top answer
1 of 5
23

Don't use caps, numbers and letters; those are all constants available from the string module.

Don't assign j since it isn't used; name the iteration variable _ instead.

Replace your length / index / slice with a random.choices.

Don't call a variable list, since 1. it shadows an existing type called list, and 2. it isn't very descriptive.

Rather than your manual, unrolled string appending, just use ''.join().

A strictly equivalent implementation could be

import random
from string import ascii_lowercase, ascii_uppercase, digits

for _ in range(4):
    fill_caps = random.choice(ascii_uppercase)
    fill_number = random.choice(digits)
    fill_letter = random.choice(ascii_lowercase)
    choices = (fill_letter, fill_caps, fill_number)
    word = ''.join(random.choices(choices, k=6))
    print(word)

but your algorithm has some odd properties that, according to your comments, you did not intend. The output word will have the choice of only one lower-case letter, one upper-case letter and one digit. The simpler and less surprising thing to do is generate a word from any of those characters:

import random
from string import ascii_lowercase, ascii_uppercase, digits

choices = ascii_lowercase + ascii_uppercase + digits

for _ in range(4):
    word = ''.join(random.choices(choices, k=6))
    print(word)
2 of 5
3

I feel like the code can be made shorter. I just don't know how.

If you want your code to be shorter, you could use a single list, like this.

import random

def rand_str(size):
    ascii_list = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
    res        = ""

    for i in range(size):
        res += ascii_list[random.randint(0, len(ascii_list) - 1)]

    return res

if __name__ == '__main__':
    # Test
    print(rand_str(16))
🌐
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 - You can mix and match these to create your desired character pool! Now let's combine everything to generate a random string. We'll use a list comprehension with range() to repeat the selection process: import random import string length = 10 alphabet = string.ascii_letters + string.digits result = ''.join(random.choice(alphabet) for _ in range(length)) print(result) >>> 'zQjzKY45Ti'
🌐
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.
🌐
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/learnpython › [beginner]how do i generate a list of random letters?
r/learnpython on Reddit: [beginner]How do i generate a list of random letters?
December 28, 2023 -

I tried using the random module but it only generates a single letter at a time. I want to generate more than 1 letters at a time. Cam i do it using the random module?

Edit: Not a list of characters but random characters

Edit2: Got the solution. Thanks everyone for the replies.

Find elsewhere
🌐
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 =
🌐
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.
🌐
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. The random module provides functions for generating random numbers and data, while the string module provides ...
🌐
YouTube
youtube.com › watch
Generate a random string with letters and digits in Python - YouTube
Use a combination of string.ascii_uppercase, string.digits and random.choices to create a list of randomly generated characters. If you need cryptographical...
Published   September 23, 2022
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-generate-random-string-of-given-length
Python - Generate Random String of given Length - GeeksforGeeks
July 11, 2025 - Python · import random import string length = 8 random_string = ''.join(random.choices(string.ascii_letters + string.digits, k=length)) print(random_string) Output · Ri7CHq8V · string.ascii_letters includes both uppercase and lowercase alphabets. string.digits adds numeric characters to the pool.
🌐
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)
January 11, 2026 - We’ll cover comparisons, and best practices. By the end of this tutorial, you will be able to use Python to efficiently generate random strings. The random module is a Python in-built module. This module implements pseudo-random number generators for various distributions like int and float-point.
🌐
Python Central
pythoncentral.io › python-snippets-how-to-generate-random-string
How to Generate a Random String | Python Central
January 4, 2017 - Check it out and feel free to use it, modify it, or completely customize it. import string from random import * min_char = 8 max_char = 12 allchar = string.ascii_letters + string.punctuation + string.digits password = "".join(choice(allchar) for x in range(randint(min_char, max_char))) print ...
🌐
Stack Abuse
stackabuse.com › how-to-generate-random-strings-in-python
How to Generate Random Strings in Python
June 27, 2023 - The secrets module, introduced in Python 3.6, provides functions for generating cryptographically secure random numbers and strings. This module is particularly useful when creating secret keys, tokens, or passwords, where security is essential. Here's an example of how to generate a cryptographically secure random string using the secrets module: import secrets import string def generate_secure_random_string(length): characters = string.ascii_letters + string.digits + string.punctuation # Generate a secure string random_string = ''.join(secrets.choice(characters) for _ in range(length)) return random_string length = 16 secure_random_string = generate_secure_random_string(length) print(secure_random_string)
🌐
GeeksforGeeks
geeksforgeeks.org › python-program-to-generate-random-string-with-uppercase-and-digits
Python Program to Generate Random String With Uppercase And Digits - GeeksforGeeks
September 5, 2024 - Besides, there are many other ... of numbers for a lottery game or slot machines. A random string generator generates an alphanumeric string consisting of random characters and digits. Let's see how we can create a random string generator. For generating random strings only with uppercase letters and digits using for loop, we require to import built-in python modules, namely ...
🌐
Quora
quora.com › In-Python-is-it-possible-to-make-a-random-string-of-numbers-like-36257-but-different-every-time
In Python, is it possible to make a random string of numbers like '36257' but different every time? - Quora
Yes. Use Python’s random or secrets modules to generate a different numeric string each run. ... random is seeded from system time by default and gives non-deterministic results each run unless you call random.seed(...).
🌐
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.
🌐
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