[英]Generating random characters in Python
I would like to generate a 16 character code我想生成一个 16 个字符的代码
The code has 5 known characters The code has 3 digits The code must be random代码有 5 个已知字符 代码有 3 位 代码必须是随机的
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 Output来自样本运行
NAA3U6MUGYRZ3DEX
If the code needs to contain at least 3 digits, but is not limited to this threshold, just change to this line:如果代码需要包含至少 3 位数字,但不限于此阈值,只需更改为这一行:
# 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如果适合您,您可以在末尾添加剩余的 2 位数字
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:您可以使用
random.choices
和random.shuffle
然后使用''.join
如下所示:
>>> 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: Output:
>>> generate_rndm()
'NAA3UTVQG8DT8NRM'
>>> generate_rndm()
'NAA3UCYBWCNQ45HR'
>>> generate_rndm()
'NAA3UIJP7W7DLOCQ'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.