python 生成随机字符串(大小写英文字母、数字组成)、生成随机的无重复字符的字符串

____tz_zs

生成随机的字符串

以下例子中,生成随机的字符串(大小写英文字母、数字组成)。

import random
import string

random_str = ''.join(random.choice(string.ascii_letters + string.digits) for _ in range(20))
print(random_str)
"""
X5V1ehPV5QaFQokclSL2
"""

生成随机的无重复字符的字符串

以下例子中,生成随机的无重复字符的字符串(大小写英文字母、数字组成),但其长度不能超过样本总长。

import random
import string

random_str = ''.join(random.sample(string.ascii_letters + string.digits, 20))
print(random_str)
"""
N4CHbuyAVPvJWGXniQUF
"""

random 模块

random.choice(seq) 从非空序列 seq 中随机选择一个元素。
random.sample(seq, k) 从序列 seq 中随机选择k个不重复的元素。

string 模块

/usr/lib/python3.7/string.py

"""
whitespace -- a string containing all ASCII whitespace
ascii_lowercase -- a string containing all ASCII lowercase letters
ascii_uppercase -- a string containing all ASCII uppercase letters
ascii_letters -- a string containing all ASCII letters
digits -- a string containing all ASCII decimal digits
hexdigits -- a string containing all ASCII hexadecimal digits
octdigits -- a string containing all ASCII octal digits
punctuation -- a string containing all ASCII punctuation characters
printable -- a string containing all ASCII characters considered printable
"""

whitespace = ' \t\n\r\v\f'
ascii_lowercase = 'abcdefghijklmnopqrstuvwxyz'
ascii_uppercase = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
ascii_letters = ascii_lowercase + ascii_uppercase
digits = '0123456789'
hexdigits = digits + 'abcdef' + 'ABCDEF'
octdigits = '01234567'
punctuation = r"""!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~"""
printable = digits + ascii_letters + punctuation + whitespace
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值