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.

🌐
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)
People also ask

What are some advanced techniques for generating random strings in Python, and when should I use them?
The secrets module and the uuid module can both be used to generate random strings in Python using more sophisticated methods. These methods offer more reliable and safe ways to generate random strings in particular circumstances.
🌐
testmuai.com
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 ...
What is a random string, and why is it important in programming?
A random string is a collection of characters produced by a randomization procedure. The string’s characters are chosen at random, with no discernible pattern or order. Programmers frequently employ random strings for a variety of tasks, including generating test data, passwords, unique IDs, and simulations.
🌐
testmuai.com
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 ...
How can I store and manage random strings securely to prevent exposure?
To store and manage random strings securely, follow these best practices:
🌐
testmuai.com
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 ...
🌐
Medium
medium.com › @ljnath › easiest-way-to-generate-random-strings-in-python-using-pyrandomstring-library-db6b5c02f7e8
Easiest way to generate random strings in Python using PyRandomString library | by ljnath | Medium
April 2, 2024 - To simplify and expedite this process, developers can take advantage of the open-source Python library known as PyRandomString. This library streamlines the creation of random data by handling all the cumbersome boilerplate code, offering straightforward yet robust methods like get_string() and get_strings() for obtaining either a single random content item or a list of random content.
🌐
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

🌐
GitHub
gist.github.com › 3658710
Generate random string in Python · GitHub
To help other coders, this is how you add character sets to the allowed variable: allowed = string.ascii_letters + string.digits · Refer: https://docs.python.org/3/library/string.html
Top answer
1 of 3
6

Python already defines a number of strings of possible characters. See string.ascii_lowercase and string.digits Source


I would use True and False instead of "yes"/"uppercase" as arguments to generator(). This function might be used by code that does directly interact with a user, so passing a string would not make sense. Additionally, the restart prompt supports a number of positive responses that are not supported by this function. You should have one layer that controls interaction with the user and one that generates a password. This will make the function cleaner as well as an easier API to work with.


Two more point about separation of concerns with generator():

  • It should return the password instead of printing it. Again, this allows the function to be used when not directly interacting with a command prompt.

  • It should throw an exception instance of calling sys.exit(). exit() will stop the python process and not allow any more execution of code. Your code is written so that multiple passwords can be generated one after another. However, if the user accidentally enters an invalid character to the first question, the application stops running instead asking the user to input a correct value. Throwing an exception would have the same result if you don't change the rest of your code, but allows you to change the code that interacts with the user to handle this case without restarting the application.


You convert length to an integer repeatedly instead of storing the value. The first validation completely ignores the result and the while loop does the conversion every time it tests if it should continue looping. This can all be solved by having length be passed in as an integer and letting the user layer handle the conversion and error cases.


Generator is already a well defined term with in Python that do something very different. The function should be renamed to generate_password() or something similar.

2 of 3
3

You are still not following the advice offered in previous answers to your questions.
Quoting from Edward's great answer on "Are there any bugs or ways to make my divisor code better?":

Separate I/O from calculation

The main purpose of the program is to factor numbers into divisors which is something that is potentially reusable. Both to make it more clear as to what the program is doing and to allow for future re-use, I'd suggest extracting the factoring part into a separate function and the have the input from the user be done within the main routine or some other input-only function.

Your password generating function, sadly, asks the user for input and thus can never be re-used outside the context of this application. Instead, make it take exactly two arguments as the only inputs: a string containing the characters to base the password on, and the length of the password:

def make_password(length, alphabet):
    return ''.join(random.choice(alphabet) for _ in range(length))

Here, random.choice(alphabet) replaces merge[random.randint(0, len(merge) - 1)]
in a more readable way.

Another repeat problem, quoting from the same answer:

Think of your user

Right now, the user has to enter "yes" or the equivalent and then enter another number to be factored. However, the prompt doesn't suggest that "y" is a valid answer. Adding that to the prompt would help the user understand what the computer is expecting. Better still, would be t eliminate that question and to simply ask for the next number with a number '0' being the user's way to specify no more numbers. Of course the prompt should be changed to tell the user of this fact.

Your user interface is basically the same: it would drive anyone who used it regularly up the wall. This is a command-line program; throw away all the input prompting and give it a command-line argument interface instead:

usage: makepwd.py [-h] [-d] [-s] [-l | -u] length

Generates passwords of the specified length, optionally including digits
and/or symbols.

positional arguments:
  length         a positive integer denoting the password length

optional arguments:
  -h, --help     show this help message and exit
  -d, --digits   include digits in the generated password
  -s, --symbols  include symbols in the generated password
  -l, --lower    use only lowercase letters
  -u, --upper    use only uppercase letters

The argparse module can take care of this for you, but you need to familiarize yourself with its semantics to understand what is going on. Let's take a look at every part individually:

def parse_args():
    parser = argparse.ArgumentParser(description=__doc__, argument_default='')
    parser.set_defaults(letters=string.ascii_letters)

We've created an argument parser and provided it the docstring of our module to use a description. In your original code, lower-case characters were used as a default. This is a bad default, instead use both lower and upper case if nothing else is specified.

    parser.add_argument('length', type=int,
                        help='a positive integer denoting the password length')

The first argument we need is the length of the password. argparse will convert the value to an int and take care of the error handling for us.

    add_const_arg = arg_adding_function_for(parser)
    add_const_arg('-d', '--digits', const=string.digits,
                  help='include digits in the generated password')
    add_const_arg('-s', '--symbols', const='#*£$+-.',
                  help='include symbols in the generated password')

Our next two arguments determine the non-alphabetical characters to include in the password.

    group = parser.add_mutually_exclusive_group()
    store_letters = arg_adding_function_for(group, dest='letters')
    store_letters('-l', '--lower', const=string.ascii_lowercase,
                  help='use only lowercase letters')
    store_letters('-u', '--upper', const=string.ascii_uppercase,
                  help='use only uppercase letters')

And the final arguments are for overriding the mixed-case default, so it's possible to generate a password containing only lower-case or only upper-case letters (in addition to the digits and symbols). These arguments are mutually exclusive: a password can not be upper-cased and lower-cased at the same time.

    return parser.parse_args()

And that's it. Almost. You may have noticed I didn't explain the arg_adding_function_for function yet. I defined it as the following higher-order helper function to simplify the above code by using functools.partial to pre-set some of the options that are common for each argument. (For flexibility, the *args parameter is included, though not technically necessary - find out more about *args and **kwargs).

def arg_adding_function_for(parser, *args, action='store_const', **kwargs):
    return functools.partial(parser.add_argument, action=action, *args, **kwargs)

The whole thing in once piece:

"""
Generates passwords of the specified length, optionally including digits and/or symbols.
"""

import argparse
import functools
import random
import string


def main():
    args = parse_args()
    password = make_password(args.length, args.letters + args.digits + args.symbols)
    print(password)


def make_password(length, alphabet):
    return ''.join(random.choice(alphabet) for _ in range(length))


def parse_args():
    parser = argparse.ArgumentParser(description=__doc__, argument_default='')
    parser.set_defaults(letters=string.ascii_letters)

    parser.add_argument('length', type=int,
                        help='a positive integer denoting the password length')

    add_const_arg = arg_adding_function_for(parser)
    add_const_arg('-d', '--digits', const=string.digits,
                  help='include digits in the generated password')
    add_const_arg('-s', '--symbols', const='#*£$+-.',
                  help='include symbols in the generated password')

    group = parser.add_mutually_exclusive_group()
    store_letters = arg_adding_function_for(group, dest='letters')
    store_letters('-l', '--lower', const=string.ascii_lowercase,
                  help='use only lowercase letters')
    store_letters('-u', '--upper', const=string.ascii_uppercase,
                  help='use only uppercase letters')
    return parser.parse_args()


def arg_adding_function_for(parser, *args, action='store_const', **kwargs):
    return functools.partial(parser.add_argument, action=action, *args, **kwargs)


if __name__ == '__main__':
    main()
Find elsewhere
🌐
Pythonhow
pythonhow.com
random
python random string-uppercase generate · python random integer · python list random · python list random · python random integer · python break while loop ·
🌐
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.
🌐
PineTools
pinetools.com › random-string-generator
Online Random string generator
Keywords: random strings generator generates chars characters letters numbers symbols
🌐
GeeksforGeeks
geeksforgeeks.org › python › how-to-generate-a-random-letter-in-python
How to generate a random letter in Python? - GeeksforGeeks
July 23, 2025 - Using random.randint(x,y) we can generate random integers from x to y. So we can randomly generate the ASCII value of one of the alphabets and then typecast them to char using chr() function ...
🌐
Replit
replit.com › home › discover › how to generate a random string in python
How to generate a random string in Python | Replit
1 month ago - If you forget to call random.seed(), Python produces a new, unpredictable sequence on each run, making it impossible to reproduce your results consistently for validation. The following code demonstrates this behavior, generating two different passwords across two consecutive runs. import random import string chars = string.ascii_letters + string.digits password = ''.join(random.choice(chars) for _ in range(8)) print(f"Run 1: {password}") password = ''.join(random.choice(chars) for _ in range(8)) print(f"Run 2: {password}") # Different result each time
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-program-match-string-random-strings-length
Generating random strings until a given string is generated - GeeksforGeeks
February 2, 2026 - DSA Python · Data Science · NumPy ... : 2 Feb, 2026 · Given a target string 'S', the task is to generate random strings of the same length as 'S' until the generated string exactly matches the target....
🌐
Python documentation
docs.python.org › 3 › library › random.html
random — Generate pseudo-random numbers
February 23, 2026 - Source code: Lib/random.py This module implements pseudo-random number generators for various distributions. For integers, there is uniform selection from a range. For sequences, there is uniform s...
🌐
Flexiple
flexiple.com › python › generate-random-string-python
How to generate a random string in Python? - Flexiple
In order to generate random strings in Python, we use the string and random modules. The string module contains Ascii string constants in various text cases, digits, etc. The random module on the other hand is used to generate pseudo-random values.
🌐
Medium
medium.com › @patelharsh7458 › python-program-for-random-string-generator-d8b2e66cbbe3
Python Program for Random String generator - Buddy - Medium
April 24, 2025 - import random import string def get_random_string(length): # choose from all lowercase letter letters = string.ascii_lowercase result_str = ''.join(random.choice(letters) for i in range(length)) print("Random string of length", length, "is:", result_str) get_random_string(10)
🌐
Better Stack
betterstack.com › community › questions › random-string-generation-in-python
Random string generation with upper case letters and digits in Python? | Better Stack Community
February 3, 2023 - You can use the random module and the string module to generate a random string of a specified length that includes upper case letters and digits.
🌐
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.
🌐
W3Schools
w3schools.com › python › ref_random_choice.asp
Python Random choice() Method
Remove List Duplicates Reverse a String Add Two Numbers · Python Examples Python Compiler Python Exercises Python Quiz Python Challenges Python Server Python Syllabus Python Study Plan Python Interview Q&A Python Bootcamp Python Certificate Python Training ... import random mylist = ["apple", "banana", "cherry"] print(random.choice(mylist)) Try it Yourself »