简体   繁体   中英

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)))

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.

You can add the remaining 2 digits at the end if it is fine for you like this

import random
import string

result1 = "NAA3U" + ''.join((random.choice(string.ascii_uppercase) for codenum in range(8))) + str(random.randint(10,99))

print(result1)

NAA3URYWMGIHG45

You can use random.choices and random.shuffle then use ''.join like below:

>>> import random
>>> import string

>>> def generate_rndm():
...    digit_char = random.choices(string.ascii_uppercase, k=9) + random.choices(string.digits, k=2)
...    random.shuffle(digit_char)
...    return "NAA3U" + ''.join(digit_char)

Output:

>>> generate_rndm()
'NAA3UTVQG8DT8NRM'

>>> generate_rndm()
'NAA3UCYBWCNQ45HR'

>>> generate_rndm()
'NAA3UIJP7W7DLOCQ'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM