Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to generate random strings with upper case letters and digits in Python?
Generating random strings with uppercase letters and digits is common in Python for creating passwords, tokens, or unique identifiers. Here are several effective methods to accomplish this ?
Using random.choices()
The random.choices() function allows repeated character selection, making it ideal for generating random strings of any length ?
import random import string # Define the length and character set length = 10 characters = string.ascii_uppercase + string.digits # Generate random string with possible duplicates result = ''.join(random.choices(characters, k=length)) print(result)
8KM2N7QX5R
Using random.choice() with Loop
This method builds the string character by character using a loop, giving you more control over the generation process ?
import random
import string
length = 10
characters = string.ascii_uppercase + string.digits
# Build string character by character
result = ''
for i in range(length):
result += random.choice(characters)
print(result)
Y9V1OVO4H4
Using random.sample()
The random.sample() function ensures no duplicate characters in the output string. Note that the maximum length is limited to 36 characters (26 letters + 10 digits) ?
import random import string length = 10 characters = string.ascii_uppercase + string.digits # Generate string without duplicate characters result = ''.join(random.sample(characters, k=length)) print(result)
VJMFQO43XL
Using UUID (Alternative Approach)
While not strictly uppercase letters and digits only, UUID provides a quick way to generate random alphanumeric strings ?
import uuid
# Generate UUID and format it
random_uuid = str(uuid.uuid4()).replace('-', '').upper()
result = random_uuid[:10] # Take first 10 characters
print(result)
3D9FF7622A
Comparison
| Method | Allows Duplicates? | Max Length | Best For |
|---|---|---|---|
random.choices() |
Yes | Unlimited | Most random strings |
random.choice() + loop |
Yes | Unlimited | Custom logic needed |
random.sample() |
No | 36 characters | Unique characters required |
uuid.uuid4() |
Varies | 32 characters | Quick unique identifiers |
Conclusion
Use random.choices() for most scenarios as it's concise and allows any length. Use random.sample() when you need unique characters only. The UUID method works well for generating unique identifiers quickly.
