Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating random characters in Python

I would like to generate a 16 character code

The code has 5 known characters The code has 3 digits The code must be random

What I did :

result1 = "NAA3U" + ''.join((random.choice(string.ascii_uppercase + string.digits) for codenum in range(11)))
like image 566
Biboune12 Avatar asked Oct 29 '25 18:10

Biboune12


1 Answers

One approach:

import random
import string

# select 2 digits at random
digits = random.choices(string.digits, k=2)

# select 9 uppercase letters at random
letters = random.choices(string.ascii_uppercase, k=9)

# shuffle both letters + digits
sample = random.sample(digits + letters, 11)

result = "NAA3U" + ''.join(sample)
print(result)

Output from a sample run

NAA3U6MUGYRZ3DEX

If the code needs to contain at least 3 digits, but is not limited to this threshold, just change to this line:

# select 11 uppercase letters and digits at random
letters = random.choices(string.ascii_uppercase + string.digits, k=11)

this will pick at random from uppercase letters and digits.

like image 135
Dani Mesejo Avatar answered Oct 31 '25 06:10

Dani Mesejo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!