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
๐ŸŒ
PYnative
pynative.com โ€บ home โ€บ python โ€บ random โ€บ generate random strings and passwords in python
Generate Random Strings and Passwords in Python
February 16, 2022 - Generate a random string of any length in Python. create a random password with lower case, upper case letters, digits, and special characters.
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

python - How to generate a random string with symbols - Stack Overflow
To generate a random string we need to use the following two Python modules. String module which contains various string constant which contains the ASCII characters of all cases. String module contains separate constants for lowercase, uppercase letters, digits, and special characters. More on stackoverflow.com
๐ŸŒ stackoverflow.com
python - Generating a random string of characters and symbols - Code Review Stack Exchange
After coding this, I was wondering if there are any ways in which I can improve upon it. It generates a random string of characters and symbols the same length as what is entered by the user. It us... More on codereview.stackexchange.com
๐ŸŒ codereview.stackexchange.com
April 22, 2024
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
April 7, 2018
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
3 weeks ago
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 ...
๐ŸŒ
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)
๐ŸŒ
Stack Abuse
stackabuse.com โ€บ how-to-generate-random-strings-in-python
How to Generate Random Strings in Python
June 27, 2023 - In this example, the generate_random_string_from_fixed_set function takes a fixed set of characters and a desired length as arguments, and it generates a random string by sampling the characters without replacement. Now that we've covered some basic and intermediate random string generation ...
๐ŸŒ
Flexiple
flexiple.com โ€บ python โ€บ generate-random-string-python
How to generate a random string in Python? - Flexiple
Here characters can not be unique. Random.sample - returns unique elements. So while generating a random string in Python, If you are okay with repeating characters you can use the first method, and the second if you want unique characters.
Find elsewhere
๐ŸŒ
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 then delved into examples of how to use these functions to generate Python random strings of different types, including alphanumeric strings, lowercase/uppercase strings, strings with specific characters/symbols, and strings of specific lengths.
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()
๐ŸŒ
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.
๐ŸŒ
Python Examples
pythonexamples.org โ€บ python-generate-random-string-of-specific-length
Generate Random String of Specific Length - Python Examples
July 23, 2025 - import random import string def randStr(chars = string.ascii_uppercase, N=8): return ''.join(random.choice(chars) for _ in range(N)) # Random string with uppercase letters only print(randStr()) # Random string of length 6 print(randStr(N=6)) Here, we generate random strings consisting only of uppercase letters by using string.ascii_uppercase. The length of the random string is customizable as shown in the examples. ... In this tutorial of Python Examples, we learned how to create a random string of a specific length from a given set of characters.
๐ŸŒ
TechGeekBuzz
techgeekbuzz.com โ€บ blog โ€บ how-to-generate-random-strings-and-passwords-in-python
How to Generate Random Strings and Passwords in Python
October 14, 2022 - import string import random #function to generate password def generate_password(upper_count=1, lower_count=1, digits_count=1, special_count=1): random_upper = "".join(random.sample(string.ascii_lowercase, k=upper_count)) random_lower = "".join(random.sample(string.ascii_uppercase, k=lower_count)) random_digits = "".join(random.sample(string.digits, k=digits_count)) random_special = "".join(random.sample(string.punctuation, k= special_count)) #add all the random chracters to form a password random_password = random_upper+random_lower+random_digits+random_special print(f"Your {len(random_passwo
๐ŸŒ
Bobby Hadz
bobbyhadz.com โ€บ blog โ€บ python-generate-random-alphanumeric-string
Generate a random alphanumeric String in Python | bobbyhadz
April 10, 2024 - Copied!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. ... Copied!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.
๐ŸŒ
LabEx
labex.io โ€บ tutorials โ€บ python-how-to-generate-random-strings-quickly-418943
How to generate random strings quickly | LabEx
October 9, 2024 - import random import string def ... ''.join(random.choice(characters) for _ in range(length)) ## Example usage random_str = generate_random_string(10) print(random_str) ## Outputs: random string of 10 characters ......
๐ŸŒ
PyPI
pypi.org โ€บ project โ€บ StringGenerator
StringGenerator ยท PyPI
July 23, 2025 - The template language is superficially similar to regular expressions but instead of defining how to match or capture strings, it defines how to generate randomized strings. A very simple invocation to produce a random string with word characters of 30 characters length: from strgen import StringGenerator as SG SG(r"[\w]{30}").render() 'wQjLVRIj1sjjslORpqLJyDObaCnDR2' ... The current package requires Python 3.6 or higher.
      ยป pip install StringGenerator
    
Published ย  Mar 20, 2021
Version ย  0.4.4
๐ŸŒ
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 - If you need specific character requirements, validate them early in your function to avoid generating invalid strings repeatedly. Here's a complete, production-ready version with error handling: import secrets import string def generate_random_string( length=12, min_uppercase=1, min_lowercase=1, min_digits=1, min_special=0 ): """ Generate a cryptographically secure random string.
๐ŸŒ
FavTutor
favtutor.com โ€บ blogs โ€บ create-random-string-password-python
Create Random String & Passwords in Python (with code)
March 1, 2023 - Before utilizing this library in Python, you must first install the special library using the "pip command." Using template language assists us in producing a random string of characters. Similar to regular expressions, the template language specifies how to create randomized strings rather than how to match or capture strings. # pip install StringGenerator from strgen import StringGenerator as SG # Generate random string with 10 characters length word random_str = strgen.StringGenerator("[\w\d]{10}").render() print(random_str) # Generate 5 unique secure tokens, each 8 characters: secure_tokens = SG("[\p\w]{8}").render_set(5) print(secure_tokens,end="\n")
๐ŸŒ
Squash
squash.io โ€บ how-to-generate-random-strings-with-upper-case-letters-and-digits-in-python
Creating Random Strings with Letters & Digits in Python
January 11, 2026 - However, instead of using the random.sample() function, we use a list comprehension with the random.choice() function to generate each character of the random string. The range of the list comprehension is set to length, which determines the ...
๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ python code that makes a word with random numbers and character in last
r/learnpython on Reddit: Python code that makes a word with random numbers and character in last
3 weeks ago -

Hello, I am new to the world of programming. I want to create a word that basically from three letters and combines with at least 2 numbers or special characters in the last of the word meaning a word that starts with three letters and ends with random numbers that do not exceed two numbers,

i don't know how to do it.

i just found this but i still cannot fix to what i need

import random

from string import ascii_lowercase, ascii_uppercase, digits

for _ in range(2):

fill_letter = random.choice(ascii_lowercase)

fill_number = random.choice(digits)

choices = (fill_letter,fill_number)

word = 'hkr'.join(random.choices(choices, k=2))

print(word)

๐ŸŒ
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 - To generate a random string with uppercase letters and digits use the secrets module. We can use the secrets.choice() function to randomly select characters from a string containing all uppercase letters and digits.