I'm trying to generate some random characters but I want to include string.letters, string.digits, and 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.
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.