[英]How to generate random character from more than one source in Python?
I'm trying to generate some random characters but I want to include string.letters, string.digits, and string.punctuation.我正在尝试生成一些随机字符,但我想包含 string.letters、string.digits 和 string.punctuation。 I can do any one of them, but how to include all three (or additional) sources/constants?我可以做其中任何一个,但是如何包含所有三个(或其他)源/常量?
import random
import string
for i in range(0,4):
print(random.choice(string.ascii_letters))
This code will choose a letter - would like to include digits and punctuation symbols also...此代码将选择一个字母 - 还想包括数字和标点符号...
Just make a source with all the things you want:只需使用您想要的所有东西制作一个来源:
import random
import string
source = string.ascii_letters + string.punctuation + string.digits
for i in range(0,4):
print(random.choice(source))
Prints:印刷:
E
)
2
h
You can just create a list with all of the characters that you want, and sample from that.您可以创建一个包含所有您想要的字符的列表,并从中采样。
#!/usr/bin/python
import random
import string
alphabet = string.ascii_letters + string.digits + string.punctuation
for i in range(0,4):
print(random.choice(alphabet))
If your lists are really big and you don't want to create a giant alphabet, you can do weighted random sampling from the alphabets (weighted by size), and then uniform random from each alphabet.如果您的列表真的很大并且您不想创建一个巨大的字母表,您可以从字母表中进行加权随机抽样(按大小加权),然后从每个字母表中进行均匀随机抽样。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.