"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Generate Random Strings of Uppercase Letters and Digits in Python?

How to Generate Random Strings of Uppercase Letters and Digits in Python?

Posted on 2025-03-11
Browse:241

How to Generate Random Strings of Uppercase Letters and Digits in Python?

Generating Random Strings Consisting of Uppercase Letters and Digits

Generating random strings containing uppercase letters and numbers is a common requirement in various applications. Here are the steps to achieve this:

  1. Import necessary modules: Begin by importing the string and random modules for ASCII characters and random number generation, respectively.
  2. Concatenate ASCII sequences: Concatenate the string.ascii_uppercase and string.digits sequences to create a string containing all uppercase letters and digits.
  3. Generate random characters: Utilize list comprehension to generate a list of random characters by choosing one from the concatenated sequence for each element in the list.
  4. Join into a string: Combine the characters in the list into a single string using Python's join method.

Example Code:

The following code implements the above steps:

import string
import random

def id_generator(size=6):
    chars = string.ascii_uppercase   string.digits
    return ''.join(random.choice(chars) for _ in range(size))

Cryptographically Secure Version:

For enhanced security, consider using the following line:

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

Python 3.6 Simplification:

If you have Python 3.6 or later, you can use the following simplified code:

''.join(random.choices(string.ascii_uppercase   string.digits, k=N))
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3