本文介绍Python3中String模块ascii_letters和digits方法,其中ascii_letters是生成所有字母,从a-z和A-Z,digits是生成所有数字0-9.string.punctuation是所有标点‘!"#$%&\‘()*+,-./:;<=>[email protected][\\]^_`{|}~‘
String模块中的常量:
string.digits:数字0~9
string.ascii_letters:所有字母(大小写)
string.lowercase:所有小写字母
string.printable:可打印字符的字符串
string.punctuation:所有标点
string.uppercase:所有大写字母
>>> import string >>> string.digits ‘0123456789‘ >>> string.letters ‘ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz‘ >>> string.lowercase ‘abcdefghijklmnopqrstuvwxyz‘ >>> string.printable ‘0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&\‘()*+,-./:;<=>[email protected][\\]^_`{|}~ \t\n\r\x0b\x0c‘ >>> string.punctuation ‘!"#$%&\‘()*+,-./:;<=>[email protected][\\]^_`{|}~‘ >>> string.uppercase ‘ABCDEFGHIJKLMNOPQRSTUVWXYZ‘
import random, string def rand_str(num, length=7): f = open(‘pwd_code.txt‘, ‘w‘) for i in range(num): chars = string.ascii_letters + string.digits+string.punctuation s = [random.choice(chars) for i in range(length)] f.write(‘{0}\n‘.format(‘‘.join(s))) f.close() if __name__ == ‘__main__‘: rand_str(200)
python2 方法一、
#!/usr/bin/env python # -*- coding: utf-8 -*- import random import string #第一种方法 seed = "[email protected]#$%^&*()_+=-" sa = [] for i in range(8): sa.append(random.choice(seed)) salt = ‘‘.join(sa) print salt
方法二、
#!/usr/bin/env python # -*- coding: utf-8 -*- import random import string salt = ‘‘.join(random.sample(string.ascii_letters + string.digits, 8)) print salt
原文地址:https://www.cnblogs.com/jackzz/p/11048640.html
时间: 2024-10-30 03:22:08