Explain Codes LogoExplain Codes Logo

Random string generation with upper case letters and digits

python
generator-expressions
random-string-generation
string-functions
Alex KataevbyAlex Kataev·Nov 8, 2024
TLDR

Get a random string of uppercase letters and digits swiftly using Python's random.sample for unique characters or random.choices to allow repetitions:

import random import string # For unique characters (no repeats, no twins): random_string = ''.join(random.sample(string.ascii_uppercase + string.digits, 10)) # Allowing repeated characters (because sometimes, two 'Z's are better than one): random_string = ''.join(random.choices(string.ascii_uppercase + string.digits, k=10)) print(random_string)

Choose random.sample for the singles club of characters, or random.choices for a deja vu friendly environment, each producing a 10-character string like '4FDGH3C2A9'. Tweak k=10 to fit your string length requirements.

Ironclad and cryptographically secure strings

If your string needs to withstand the scrutiny of complex cryptographic applications, Python's secrets module is your backstage pass. Here's how you can orchestrate a secure string concert:

import secrets import string secure_string = ''.join(secrets.choice(string.ascii_uppercase + string.digits) for i in range(10)) print(secure_string)

Consider avoiding random.choices if your string will be handling passwords, tokens, or decrypting the recipe of grandma's secret pie.

Cooking up a custom string function

Do you ever feel like you're spinning in circles? A custom function, id_generator, helps you break out of the loop by dreaming up random strings in a snap. Feed it both length and character set:

import random import string def id_generator(size=10, chars=string.ascii_uppercase + string.digits): return ''.join(random.choice(chars) for _ in range(size)) # Generate string: print(id_generator()) # By order of the Peaky Blinders. # Generate a shortie or longfellow: print(id_generator(5)) # Short, but memorable. print(id_generator(15)) # Because size matters... sometimes.

Wrapped up in a function, string generation is just a call away, armed and ready to join any Python code party.

Juggling UUIDs like a pro

UUIDs are like that cool kid with a rare trading card. Python's uuid module lets you strut around with a unique UUID, in uppercase and hexadecimal:

import uuid uuid_string = uuid.uuid4().hex.upper()[:10] print(uuid_string) # Say hello to my little UUID

Note

UUIDs might be unique, but their length is set in stone. Luckily, Python goes slice, slice, chop, chop to serve your UUID at the perfect length.

Efficiency is key

Size matters, not always in length, but sometimes in memory. For when you're tight on efficiency, go for generator expressions.

import random import string # Embrace the magic of generator expression: efficient_random_string = ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(10))

This trades your square brackets for parentheses, banishing the evil memory-consuming list from your kingdom.

System randomness: Under the hood

Feeling adventurous? Dive into system-level sources of pseudo-randomness. Unix-based systems set the table with /dev/urandom, served by Python's os.urandom function. Windows? Windows says CryptGenRandom(): Python via the cryptography library.

Expanding horizons: Custom character sets

Feeling a tad fancy? Dress up your random strings with an expanded character set. Give your repeated characters some more screen time with random.sample.

import random import string expanded_chars = (string.ascii_uppercase + string.digits) * 3 unique_expanded_string = ''.join(random.sample(expanded_chars, 10)) print(unique_expanded_string) # Everyone loves some extra sparkles!

Dive into a pool of characters to explore, making random.sample much more exciting!