简体   繁体   English

如何从 Python 中的多个来源生成随机字符?

[英]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.

相关问题 如何在python中使用随机森林预测多个类? - How to predict more than one class with random forest in python? python如何用多个字符分割字符串? - python how to split string with more than one character? 如何替换字符串中的多个字符 Python - How do I replace more than one character in a string Python 从列表中生成随机元素,每个元素不超过一次重复 - Generate random element from list with no more than one repetition of one element 如何使用 python 函数从列表中生成多个列表 - How to generate more than one list from a list, using python functions 如何在不使用python中的多个if / else语句的情况下多次生成随机列表? - How do I generate a random list more than once without using multiple if/else statements in python? "Python - 如何使用 slice 方法、find 和 rfind 在 python 上删除多个字符" - Python - How do i delete more than one character on python using slice method, find and rfind 如何在Python中从嵌套字典打印多个值 - How to print more than one value from nested dict in Python 如何在Python中从字符串中查找多个子字符串 - How to find more than one substring from a string in Python 如何从Python中删除队列中的多个元素? - How to remove more than one element from a queue in Python?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM